facture.class.php 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646
  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@capnetworks.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-2016 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 Ferran Marcet <fmarcet@2byte.es>
  18. *
  19. * This program is free software; you can redistribute it and/or modify
  20. * it under the terms of the GNU General Public License as published by
  21. * the Free Software Foundation; either version 3 of the License, or
  22. * (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU General Public License
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * \file htdocs/compta/facture/class/facture.class.php
  34. * \ingroup facture
  35. * \brief File of class to manage invoices
  36. */
  37. include_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
  42. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  43. /**
  44. * Class to manage invoices
  45. */
  46. class Facture extends CommonInvoice
  47. {
  48. public $element='facture';
  49. public $table_element='facture';
  50. public $table_element_line = 'facturedet';
  51. public $fk_element = 'fk_facture';
  52. protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  53. /**
  54. * {@inheritdoc}
  55. */
  56. protected $table_ref_field = 'facnumber';
  57. public $socid;
  58. public $author;
  59. public $fk_user_author;
  60. public $fk_user_valid;
  61. public $date; // Date invoice
  62. public $date_creation; // Creation date
  63. public $date_validation; // Validation date
  64. public $datem;
  65. public $ref_client;
  66. public $ref_int;
  67. //Check constants for types
  68. public $type = self::TYPE_STANDARD;
  69. //var $amount;
  70. public $remise_absolue;
  71. public $remise_percent;
  72. public $total_ht=0;
  73. public $total_tva=0;
  74. public $total_ttc=0;
  75. public $revenuestamp;
  76. //! Fermeture apres paiement partiel: discount_vat, badcustomer, abandon
  77. //! Fermeture alors que aucun paiement: replaced (si remplace), abandon
  78. public $close_code;
  79. //! Commentaire si mis a paye sans paiement complet
  80. public $close_note;
  81. //! 1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code)
  82. public $paye;
  83. //! id of source invoice if replacement invoice or credit note
  84. public $fk_facture_source;
  85. public $linked_objects=array();
  86. public $date_lim_reglement;
  87. public $cond_reglement_code; // Code in llx_c_paiement
  88. public $mode_reglement_code; // Code in llx_c_paiement
  89. public $fk_bank; // Field to store bank id to use when payment mode is withdraw
  90. /**
  91. * @deprecated
  92. */
  93. public $products=array();
  94. /**
  95. * @var FactureLigne[]
  96. */
  97. public $lines=array();
  98. public $line;
  99. public $extraparams=array();
  100. public $specimen;
  101. public $fac_rec;
  102. // Multicurrency
  103. public $fk_multicurrency;
  104. public $multicurrency_code;
  105. public $multicurrency_tx;
  106. public $multicurrency_total_ht;
  107. public $multicurrency_total_tva;
  108. public $multicurrency_total_ttc;
  109. /**
  110. * @var int Situation cycle reference number
  111. */
  112. public $situation_cycle_ref;
  113. /**
  114. * @var int Situation counter inside the cycle
  115. */
  116. public $situation_counter;
  117. /**
  118. * @var bool Final situation flag
  119. */
  120. public $situation_final;
  121. /**
  122. * @var array Table of previous situations
  123. */
  124. public $tab_previous_situation_invoice=array();
  125. /**
  126. * @var array Table of next situations
  127. */
  128. public $tab_next_situation_invoice=array();
  129. public $oldcopy;
  130. /**
  131. * Standard invoice
  132. */
  133. const TYPE_STANDARD = 0;
  134. /**
  135. * Replacement invoice
  136. */
  137. const TYPE_REPLACEMENT = 1;
  138. /**
  139. * Credit note invoice
  140. */
  141. const TYPE_CREDIT_NOTE = 2;
  142. /**
  143. * Deposit invoice
  144. */
  145. const TYPE_DEPOSIT = 3;
  146. /**
  147. * Proforma invoice (should not be used. a proforma is an order)
  148. */
  149. const TYPE_PROFORMA = 4;
  150. /**
  151. * Situation invoice
  152. */
  153. const TYPE_SITUATION = 5;
  154. /**
  155. * Draft
  156. */
  157. const STATUS_DRAFT = 0;
  158. /**
  159. * Validated (need to be paid)
  160. */
  161. const STATUS_VALIDATED = 1;
  162. /**
  163. * Classified paid.
  164. * If paid partially, $this->close_code can be:
  165. * - CLOSECODE_DISCOUNTVAT
  166. * - CLOSECODE_BADDEBT
  167. * If paid completelly, this->close_code will be null
  168. */
  169. const STATUS_CLOSED = 2;
  170. /**
  171. * Classified abandoned and no payment done.
  172. * $this->close_code can be:
  173. * - CLOSECODE_BADDEBT
  174. * - CLOSECODE_ABANDONED
  175. * - CLOSECODE_REPLACED
  176. */
  177. const STATUS_ABANDONED = 3;
  178. const CLOSECODE_DISCOUNTVAT = 'discount_vat';
  179. const CLOSECODE_BADDEBT = 'badcustomer';
  180. const CLOSECODE_ABANDONED = 'abandon';
  181. const CLOSECODE_REPLACED = 'replaced';
  182. /**
  183. * Constructor
  184. *
  185. * @param DoliDB $db Database handler
  186. */
  187. function __construct($db)
  188. {
  189. $this->db = $db;
  190. }
  191. /**
  192. * Create invoice in database
  193. * Note: this->ref can be set or empty. If empty, we will use "(PROV)"
  194. * Note: this->fac_rec must be set to create from recurring invoice
  195. *
  196. * @param User $user Object user that create
  197. * @param int $notrigger 1=Does not execute triggers, 0 otherwise
  198. * @param int $forceduedate 1=Do not recalculate due date from payment condition but force it with value
  199. * @return int <0 if KO, >0 if OK
  200. */
  201. function create($user,$notrigger=0,$forceduedate=0)
  202. {
  203. global $langs,$conf,$mysoc,$hookmanager;
  204. $error=0;
  205. // Clean parameters
  206. if (empty($this->type)) $this->type = self::TYPE_STANDARD;
  207. $this->ref_client=trim($this->ref_client);
  208. $this->note=(isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
  209. $this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
  210. $this->note_public=trim($this->note_public);
  211. if (! $this->cond_reglement_id) $this->cond_reglement_id = 0;
  212. if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
  213. $this->brouillon = 1;
  214. // Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
  215. if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
  216. else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  217. if (empty($this->fk_multicurrency))
  218. {
  219. $this->multicurrency_code = $conf->currency;
  220. $this->fk_multicurrency = 0;
  221. $this->multicurrency_tx = 1;
  222. }
  223. dol_syslog(get_class($this)."::create user=".$user->id);
  224. // Check parameters
  225. if (empty($this->date) || empty($user->id))
  226. {
  227. $this->error="ErrorBadParameter";
  228. dol_syslog(get_class($this)."::create Try to create an invoice with an empty parameter (user, date, ...)", LOG_ERR);
  229. return -3;
  230. }
  231. $soc = new Societe($this->db);
  232. $result=$soc->fetch($this->socid);
  233. if ($result < 0)
  234. {
  235. $this->error="Failed to fetch company: ".$soc->error;
  236. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  237. return -2;
  238. }
  239. $now=dol_now();
  240. $this->db->begin();
  241. // Create invoice from a template invoice
  242. if ($this->fac_rec > 0)
  243. {
  244. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
  245. $_facrec = new FactureRec($this->db);
  246. $result=$_facrec->fetch($this->fac_rec);
  247. $this->socid = $_facrec->socid;
  248. // 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
  249. $this->fk_project = GETPOST('projectid','int') > 0 ? GETPOST('projectid','int') : $_facrec->fk_project;
  250. $this->note_public = GETPOST('note_public') ? GETPOST('note_public') : $_facrec->note_public;
  251. $this->note_private = GETPOST('note_private') ? GETPOST('note_private') : $_facrec->note_private;
  252. $this->modelpdf = GETPOST('model') ? GETPOST('model') : $_facrec->modelpdf;
  253. $this->cond_reglement_id = GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $_facrec->cond_reglement_id;
  254. $this->mode_reglement_id = GETPOST('mode_reglement_id') > 0 ? GETPOST('mode_reglement_id') : $_facrec->mode_reglement_id;
  255. $this->fk_account = GETPOST('fk_account') > 0 ? GETPOST('fk_account') : $_facrec->fk_account;
  256. // Fields always coming from template
  257. $this->remise_absolue = $_facrec->remise_absolue;
  258. $this->remise_percent = $_facrec->remise_percent;
  259. $this->fk_incoterms = $_facrec->fk_incoterms;
  260. $this->location_incoterms= $_facrec->location_incoterms;
  261. // Clean parameters
  262. if (! $this->type) $this->type = self::TYPE_STANDARD;
  263. $this->ref_client=trim($this->ref_client);
  264. $this->note_public=trim($this->note_public);
  265. $this->note_private=trim($this->note_private);
  266. $this->note_private=dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
  267. //if (! $this->remise) $this->remise = 0;
  268. if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
  269. $this->brouillon = 1;
  270. $forceduedate = $this->calculate_date_lim_reglement();
  271. // For recurrn invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
  272. if ($_facrec->frequency > 0)
  273. {
  274. $next_date = $_facrec->getNextDate(); // Calculate next date
  275. $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date');
  276. //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
  277. $_facrec->setNextDate($next_date,1);
  278. }
  279. }
  280. // Define due date if not already defined
  281. $datelim=(empty($forceduedate)?$this->calculate_date_lim_reglement():$forceduedate);
  282. // Insert into database
  283. $socid = $this->socid;
  284. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
  285. $sql.= " facnumber";
  286. $sql.= ", entity";
  287. $sql.= ", ref_ext";
  288. $sql.= ", type";
  289. $sql.= ", fk_soc";
  290. $sql.= ", datec";
  291. $sql.= ", remise_absolue";
  292. $sql.= ", remise_percent";
  293. $sql.= ", datef";
  294. $sql.= ", date_pointoftax";
  295. $sql.= ", note_private";
  296. $sql.= ", note_public";
  297. $sql.= ", ref_client, ref_int";
  298. $sql.= ", fk_account";
  299. $sql.= ", fk_facture_source, fk_user_author, fk_projet";
  300. $sql.= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
  301. $sql.= ", situation_cycle_ref, situation_counter, situation_final";
  302. $sql.= ", fk_incoterms, location_incoterms";
  303. $sql.= ", fk_multicurrency";
  304. $sql.= ", multicurrency_code";
  305. $sql.= ", multicurrency_tx";
  306. $sql.= ")";
  307. $sql.= " VALUES (";
  308. $sql.= "'(PROV)'";
  309. $sql.= ", ".$conf->entity;
  310. $sql.= ", ".($this->ref_ext?"'".$this->db->escape($this->ref_ext)."'":"null");
  311. $sql.= ", '".$this->db->escape($this->type)."'";
  312. $sql.= ", '".$socid."'";
  313. $sql.= ", '".$this->db->idate($now)."'";
  314. $sql.= ", ".($this->remise_absolue>0?$this->remise_absolue:'NULL');
  315. $sql.= ", ".($this->remise_percent>0?$this->remise_percent:'NULL');
  316. $sql.= ", '".$this->db->idate($this->date)."'";
  317. $sql.= ", ".(strval($this->date_pointoftax)!='' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null');
  318. $sql.= ", ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null");
  319. $sql.= ", ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null");
  320. $sql.= ", ".($this->ref_client?"'".$this->db->escape($this->ref_client)."'":"null");
  321. $sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
  322. $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
  323. $sql.= ", ".($this->fk_facture_source?"'".$this->db->escape($this->fk_facture_source)."'":"null");
  324. $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"null");
  325. $sql.= ", ".($this->fk_project?$this->fk_project:"null");
  326. $sql.= ", ".$this->cond_reglement_id;
  327. $sql.= ", ".$this->mode_reglement_id;
  328. $sql.= ", '".$this->db->idate($datelim)."', '".$this->db->escape($this->modelpdf)."'";
  329. $sql.= ", ".($this->situation_cycle_ref?"'".$this->db->escape($this->situation_cycle_ref)."'":"null");
  330. $sql.= ", ".($this->situation_counter?"'".$this->db->escape($this->situation_counter)."'":"null");
  331. $sql.= ", ".($this->situation_final?$this->situation_final:0);
  332. $sql.= ", ".(int) $this->fk_incoterms;
  333. $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
  334. $sql.= ", ".(int) $this->fk_multicurrency;
  335. $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
  336. $sql.= ", ".(double) $this->multicurrency_tx;
  337. $sql.=")";
  338. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  339. $resql=$this->db->query($sql);
  340. if ($resql)
  341. {
  342. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
  343. // Update ref with new one
  344. $this->ref='(PROV'.$this->id.')';
  345. $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET facnumber='".$this->ref."' WHERE rowid=".$this->id;
  346. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  347. $resql=$this->db->query($sql);
  348. if (! $resql) $error++;
  349. // Add object linked
  350. if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
  351. {
  352. foreach($this->linked_objects as $origin => $origin_id)
  353. {
  354. $ret = $this->add_object_linked($origin, $origin_id);
  355. if (! $ret)
  356. {
  357. dol_print_error($this->db);
  358. $error++;
  359. }
  360. // TODO mutualiser
  361. if ($origin == 'commande')
  362. {
  363. // On recupere les differents contact interne et externe
  364. $order = new Commande($this->db);
  365. $order->id = $origin_id;
  366. // On recupere le commercial suivi propale
  367. $this->userid = $order->getIdcontact('internal', 'SALESREPFOLL');
  368. if ($this->userid)
  369. {
  370. //On passe le commercial suivi commande en commercial suivi paiement
  371. $this->add_contact($this->userid[0], 'SALESREPFOLL', 'internal');
  372. }
  373. // On recupere le contact client facturation commande
  374. $this->contactid = $order->getIdcontact('external', 'BILLING');
  375. if ($this->contactid)
  376. {
  377. //On passe le contact client facturation commande en contact client facturation
  378. $this->add_contact($this->contactid[0], 'BILLING', 'external');
  379. }
  380. }
  381. }
  382. }
  383. /*
  384. * Insert lines of invoices into database
  385. */
  386. if (count($this->lines) && is_object($this->lines[0])) // If this->lines is array on InvoiceLines (preferred mode)
  387. {
  388. $fk_parent_line = 0;
  389. dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
  390. foreach ($this->lines as $i => $val)
  391. {
  392. $newinvoiceline=$this->lines[$i];
  393. $newinvoiceline->fk_facture=$this->id;
  394. $newinvoiceline->origin = $this->element;
  395. $newinvoiceline->origin_id = $this->lines[$i]->id;
  396. if ($result >= 0 && ($newinvoiceline->info_bits & 0x01) == 0) // We keep only lines with first bit = 0
  397. {
  398. // Reset fk_parent_line for no child products and special product
  399. if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
  400. $fk_parent_line = 0;
  401. }
  402. $newinvoiceline->fk_parent_line=$fk_parent_line;
  403. $result=$newinvoiceline->insert();
  404. // Defined the new fk_parent_line
  405. if ($result > 0 && $newinvoiceline->product_type == 9) {
  406. $fk_parent_line = $result;
  407. }
  408. }
  409. if ($result < 0)
  410. {
  411. $this->error=$newinvoiceline->error;
  412. $error++;
  413. break;
  414. }
  415. }
  416. }
  417. else // If this->lines is not object of invoice lines
  418. {
  419. $fk_parent_line = 0;
  420. dol_syslog("There is ".count($this->lines)." lines that are array lines");
  421. foreach ($this->lines as $i => $val)
  422. {
  423. if (($this->lines[$i]->info_bits & 0x01) == 0) // We keep only lines with first bit = 0
  424. {
  425. // Reset fk_parent_line for no child products and special product
  426. if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) {
  427. $fk_parent_line = 0;
  428. }
  429. $result = $this->addline(
  430. $this->lines[$i]->desc,
  431. $this->lines[$i]->subprice,
  432. $this->lines[$i]->qty,
  433. $this->lines[$i]->tva_tx,
  434. $this->lines[$i]->localtax1_tx,
  435. $this->lines[$i]->localtax2_tx,
  436. $this->lines[$i]->fk_product,
  437. $this->lines[$i]->remise_percent,
  438. $this->lines[$i]->date_start,
  439. $this->lines[$i]->date_end,
  440. $this->lines[$i]->fk_code_ventilation,
  441. $this->lines[$i]->info_bits,
  442. $this->lines[$i]->fk_remise_except,
  443. 'HT',
  444. 0,
  445. $this->lines[$i]->product_type,
  446. $this->lines[$i]->rang,
  447. $this->lines[$i]->special_code,
  448. $this->element,
  449. $this->lines[$i]->id,
  450. $fk_parent_line,
  451. $this->lines[$i]->fk_fournprice,
  452. $this->lines[$i]->pa_ht,
  453. $this->lines[$i]->label,
  454. $this->lines[$i]->array_options,
  455. $this->lines[$i]->situation_percent,
  456. $this->lines[$i]->fk_prev_id,
  457. $this->lines[$i]->fk_unit
  458. );
  459. if ($result < 0)
  460. {
  461. $this->error=$this->db->lasterror();
  462. dol_print_error($this->db);
  463. $this->db->rollback();
  464. return -1;
  465. }
  466. // Defined the new fk_parent_line
  467. if ($result > 0 && $this->lines[$i]->product_type == 9) {
  468. $fk_parent_line = $result;
  469. }
  470. }
  471. }
  472. }
  473. /*
  474. * Insert lines of predefined invoices
  475. */
  476. if (! $error && $this->fac_rec > 0)
  477. {
  478. foreach ($_facrec->lines as $i => $val)
  479. {
  480. if ($_facrec->lines[$i]->fk_product)
  481. {
  482. $prod = new Product($this->db);
  483. $res=$prod->fetch($_facrec->lines[$i]->fk_product);
  484. }
  485. $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
  486. $tva_npr = get_default_npr($mysoc,$soc,$prod->id);
  487. if (empty($tva_tx)) $tva_npr=0;
  488. $localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
  489. $localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
  490. $result_insert = $this->addline(
  491. $_facrec->lines[$i]->desc,
  492. $_facrec->lines[$i]->subprice,
  493. $_facrec->lines[$i]->qty,
  494. $tva_tx,
  495. $localtax1_tx,
  496. $localtax2_tx,
  497. $_facrec->lines[$i]->fk_product,
  498. $_facrec->lines[$i]->remise_percent,
  499. '','',0,$tva_npr,'','HT',0,
  500. $_facrec->lines[$i]->product_type,
  501. $_facrec->lines[$i]->rang,
  502. $_facrec->lines[$i]->special_code,
  503. '',
  504. 0,
  505. 0,
  506. null,
  507. 0,
  508. $_facrec->lines[$i]->label,
  509. null,
  510. $_facrec->lines[$i]->situation_percent,
  511. '',
  512. $_facrec->lines[$i]->fk_unit
  513. );
  514. if ( $result_insert < 0)
  515. {
  516. $error++;
  517. $this->error=$this->db->error();
  518. break;
  519. }
  520. }
  521. }
  522. if (! $error)
  523. {
  524. $result=$this->update_price(1);
  525. if ($result > 0)
  526. {
  527. $action='create';
  528. // Actions on extra fields (by external module or standard code)
  529. // TODO le hook fait double emploi avec le trigger !!
  530. $hookmanager->initHooks(array('invoicedao'));
  531. $parameters=array('invoiceid'=>$this->id);
  532. $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  533. if (empty($reshook))
  534. {
  535. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  536. {
  537. $result=$this->insertExtraFields();
  538. if ($result < 0)
  539. {
  540. $error++;
  541. }
  542. }
  543. }
  544. else if ($reshook < 0) $error++;
  545. // Call trigger
  546. $result=$this->call_trigger('BILL_CREATE',$user);
  547. if ($result < 0) $error++;
  548. // End call triggers
  549. if (! $error)
  550. {
  551. $this->db->commit();
  552. return $this->id;
  553. }
  554. else
  555. {
  556. $this->db->rollback();
  557. return -4;
  558. }
  559. }
  560. else
  561. {
  562. $this->error=$langs->trans('FailedToUpdatePrice');
  563. $this->db->rollback();
  564. return -3;
  565. }
  566. }
  567. else
  568. {
  569. dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
  570. $this->db->rollback();
  571. return -2;
  572. }
  573. }
  574. else
  575. {
  576. $this->error=$this->db->error();
  577. $this->db->rollback();
  578. return -1;
  579. }
  580. }
  581. /**
  582. * Create a new invoice in database from current invoice
  583. *
  584. * @param User $user Object user that ask creation
  585. * @param int $invertdetail Reverse sign of amounts for lines
  586. * @return int <0 if KO, >0 if OK
  587. */
  588. function createFromCurrent($user,$invertdetail=0)
  589. {
  590. global $conf;
  591. // Charge facture source
  592. $facture=new Facture($this->db);
  593. $facture->fk_facture_source = $this->fk_facture_source;
  594. $facture->type = $this->type;
  595. $facture->socid = $this->socid;
  596. $facture->date = $this->date;
  597. $facture->date_pointoftax = $this->date_pointoftax;
  598. $facture->note_public = $this->note_public;
  599. $facture->note_private = $this->note_private;
  600. $facture->ref_client = $this->ref_client;
  601. $facture->modelpdf = $this->modelpdf;
  602. $facture->fk_project = $this->fk_project;
  603. $facture->cond_reglement_id = $this->cond_reglement_id;
  604. $facture->mode_reglement_id = $this->mode_reglement_id;
  605. $facture->remise_absolue = $this->remise_absolue;
  606. $facture->remise_percent = $this->remise_percent;
  607. $facture->origin = $this->origin;
  608. $facture->origin_id = $this->origin_id;
  609. $facture->lines = $this->lines; // Tableau des lignes de factures
  610. $facture->products = $this->lines; // Tant que products encore utilise
  611. $facture->situation_counter = $this->situation_counter;
  612. $facture->situation_cycle_ref=$this->situation_cycle_ref;
  613. $facture->situation_final = $this->situation_final;
  614. // Loop on each line of new invoice
  615. foreach($facture->lines as $i => $line)
  616. {
  617. $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
  618. if ($invertdetail)
  619. {
  620. $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
  621. $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
  622. $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
  623. $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
  624. $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
  625. $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
  626. }
  627. }
  628. dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
  629. $facid = $facture->create($user);
  630. if ($facid <= 0)
  631. {
  632. $this->error=$facture->error;
  633. $this->errors=$facture->errors;
  634. }
  635. elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION))
  636. {
  637. $this->fetchObjectLinked('', '', $object->id, 'facture');
  638. foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object)
  639. {
  640. foreach ($Tfk_object as $fk_object)
  641. {
  642. $facture->add_object_linked($typeObject, $fk_object);
  643. }
  644. }
  645. $facture->add_object_linked('facture', $this->fk_facture_source);
  646. }
  647. return $facid;
  648. }
  649. /**
  650. * Load an object from its id and create a new one in database
  651. *
  652. * @param int $socid Id of thirdparty
  653. * @return int New id of clone
  654. */
  655. function createFromClone($socid=0)
  656. {
  657. global $user,$hookmanager;
  658. $error=0;
  659. $this->context['createfromclone'] = 'createfromclone';
  660. $this->db->begin();
  661. // get extrafields so they will be clone
  662. foreach($this->lines as $line)
  663. $line->fetch_optionals($line->rowid);
  664. // Load source object
  665. $objFrom = clone $this;
  666. // Change socid if needed
  667. if (! empty($socid) && $socid != $this->socid)
  668. {
  669. $objsoc = new Societe($this->db);
  670. if ($objsoc->fetch($socid)>0)
  671. {
  672. $this->socid = $objsoc->id;
  673. $this->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
  674. $this->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
  675. $this->fk_project = '';
  676. $this->fk_delivery_address = '';
  677. }
  678. // TODO Change product price if multi-prices
  679. }
  680. $this->id=0;
  681. $this->statut= self::STATUS_DRAFT;
  682. // Clear fields
  683. $this->date = dol_now(); // Date of invoice is set to current date when cloning. // TODO Best is to ask date into confirm box
  684. $this->user_author = $user->id;
  685. $this->user_valid = '';
  686. $this->fk_facture_source = 0;
  687. $this->date_creation = '';
  688. $this->date_validation = '';
  689. $this->ref_client = '';
  690. $this->close_code = '';
  691. $this->close_note = '';
  692. $this->products = $this->lines; // Tant que products encore utilise
  693. // Loop on each line of new invoice
  694. foreach($this->lines as $i => $line)
  695. {
  696. if (($this->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts
  697. {
  698. unset($this->lines[$i]);
  699. unset($this->products[$i]); // Tant que products encore utilise
  700. }
  701. }
  702. // Create clone
  703. $result=$this->create($user);
  704. if ($result < 0) $error++;
  705. else {
  706. // copy internal contacts
  707. if ($this->copy_linked_contact($objFrom, 'internal') < 0)
  708. $error++;
  709. // copy external contacts if same company
  710. elseif ($objFrom->socid == $this->socid)
  711. {
  712. if ($this->copy_linked_contact($objFrom, 'external') < 0)
  713. $error++;
  714. }
  715. }
  716. if (! $error)
  717. {
  718. // Hook of thirdparty module
  719. if (is_object($hookmanager))
  720. {
  721. $parameters=array('objFrom'=>$objFrom);
  722. $action='';
  723. $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  724. if ($reshook < 0) $error++;
  725. }
  726. // Call trigger
  727. $result=$this->call_trigger('BILL_CLONE',$user);
  728. if ($result < 0) $error++;
  729. // End call triggers
  730. }
  731. unset($this->context['createfromclone']);
  732. // End
  733. if (! $error)
  734. {
  735. $this->db->commit();
  736. return $this->id;
  737. }
  738. else
  739. {
  740. $this->db->rollback();
  741. return -1;
  742. }
  743. }
  744. /**
  745. * Load an object from an order and create a new invoice into database
  746. *
  747. * @param Object $object Object source
  748. * @return int <0 if KO, 0 if nothing done, 1 if OK
  749. */
  750. function createFromOrder($object)
  751. {
  752. global $user,$hookmanager;
  753. $error=0;
  754. // Closed order
  755. $this->date = dol_now();
  756. $this->source = 0;
  757. $num=count($object->lines);
  758. for ($i = 0; $i < $num; $i++)
  759. {
  760. $line = new FactureLigne($this->db);
  761. $line->libelle = $object->lines[$i]->libelle;
  762. $line->label = $object->lines[$i]->label;
  763. $line->desc = $object->lines[$i]->desc;
  764. $line->subprice = $object->lines[$i]->subprice;
  765. $line->total_ht = $object->lines[$i]->total_ht;
  766. $line->total_tva = $object->lines[$i]->total_tva;
  767. $line->total_ttc = $object->lines[$i]->total_ttc;
  768. $line->tva_tx = $object->lines[$i]->tva_tx;
  769. $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
  770. $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
  771. $line->qty = $object->lines[$i]->qty;
  772. $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
  773. $line->remise_percent = $object->lines[$i]->remise_percent;
  774. $line->fk_product = $object->lines[$i]->fk_product;
  775. $line->info_bits = $object->lines[$i]->info_bits;
  776. $line->product_type = $object->lines[$i]->product_type;
  777. $line->rang = $object->lines[$i]->rang;
  778. $line->special_code = $object->lines[$i]->special_code;
  779. $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
  780. $line->fk_unit = $object->lines[$i]->fk_unit;
  781. $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
  782. $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);
  783. $line->pa_ht = $marginInfos[0];
  784. // get extrafields from original line
  785. $object->lines[$i]->fetch_optionals($object->lines[$i]->rowid);
  786. foreach($object->lines[$i]->array_options as $options_key => $value)
  787. $line->array_options[$options_key] = $value;
  788. $this->lines[$i] = $line;
  789. }
  790. $this->socid = $object->socid;
  791. $this->fk_project = $object->fk_project;
  792. $this->cond_reglement_id = $object->cond_reglement_id;
  793. $this->mode_reglement_id = $object->mode_reglement_id;
  794. $this->availability_id = $object->availability_id;
  795. $this->demand_reason_id = $object->demand_reason_id;
  796. $this->date_livraison = $object->date_livraison;
  797. $this->fk_delivery_address = $object->fk_delivery_address;
  798. $this->contact_id = $object->contactid;
  799. $this->ref_client = $object->ref_client;
  800. $this->note_private = $object->note_private;
  801. $this->note_public = $object->note_public;
  802. $this->origin = $object->element;
  803. $this->origin_id = $object->id;
  804. // get extrafields from original line
  805. $object->fetch_optionals($object->id);
  806. foreach($object->array_options as $options_key => $value)
  807. $this->array_options[$options_key] = $value;
  808. // Possibility to add external linked objects with hooks
  809. $this->linked_objects[$this->origin] = $this->origin_id;
  810. if (! empty($object->other_linked_objects) && is_array($object->other_linked_objects))
  811. {
  812. $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
  813. }
  814. $ret = $this->create($user);
  815. if ($ret > 0)
  816. {
  817. // Actions hooked (by external module)
  818. $hookmanager->initHooks(array('invoicedao'));
  819. $parameters=array('objFrom'=>$object);
  820. $action='';
  821. $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  822. if ($reshook < 0) $error++;
  823. if (! $error)
  824. {
  825. return 1;
  826. }
  827. else return -1;
  828. }
  829. else return -1;
  830. }
  831. /**
  832. * Return clicable link of object (with eventually picto)
  833. *
  834. * @param int $withpicto Add picto into link
  835. * @param string $option Where point the link
  836. * @param int $max Maxlength of ref
  837. * @param int $short 1=Return just URL
  838. * @param string $moretitle Add more text to title tooltip
  839. * @return string String with URL
  840. */
  841. function getNomUrl($withpicto=0,$option='',$max=0,$short=0,$moretitle='')
  842. {
  843. global $langs, $conf;
  844. $result='';
  845. if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
  846. else $url = DOL_URL_ROOT.'/compta/facture.php?facid='.$this->id;
  847. if ($short) return $url;
  848. $picto='bill';
  849. if ($this->type == self::TYPE_REPLACEMENT) $picto.='r'; // Replacement invoice
  850. if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a'; // Credit note
  851. if ($this->type == self::TYPE_DEPOSIT) $picto.='d'; // Deposit invoice
  852. $label = '<u>' . $langs->trans("ShowInvoice") . '</u>';
  853. if (! empty($this->ref))
  854. $label .= '<br><b>'.$langs->trans('Ref') . ':</b> ' . $this->ref;
  855. if (! empty($this->ref_client))
  856. $label .= '<br><b>' . $langs->trans('RefCustomer') . ':</b> ' . $this->ref_client;
  857. if (! empty($this->total_ht))
  858. $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  859. if (! empty($this->total_tva))
  860. $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  861. if (! empty($this->total_ttc))
  862. $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  863. if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
  864. if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
  865. if ($this->type == self::TYPE_DEPOSIT) $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
  866. if ($this->type == self::TYPE_SITUATION) $label=$langs->transnoentitiesnoconv("ShowInvoiceSituation").': '.$this->ref;
  867. if ($moretitle) $label.=' - '.$moretitle;
  868. $linkstart='<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
  869. $linkend='</a>';
  870. if ($withpicto) $result.=($linkstart.img_object(($max?dol_trunc($label,$max):$label), $picto, 'class="classfortooltip"').$linkend);
  871. if ($withpicto && $withpicto != 2) $result.=' ';
  872. if ($withpicto != 2) $result.=$linkstart.($max?dol_trunc($this->ref,$max):$this->ref).$linkend;
  873. return $result;
  874. }
  875. /**
  876. * Get object and lines from database
  877. *
  878. * @param int $rowid Id of object to load
  879. * @param string $ref Reference of invoice
  880. * @param string $ref_ext External reference of invoice
  881. * @param int $ref_int Internal reference of other object
  882. * @param bool $fetch_situation Fetch the previous and next situation in $tab_previous_situation_invoice and $tab_next_situation_invoice
  883. * @return int >0 if OK, <0 if KO, 0 if not found
  884. */
  885. function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $fetch_situation=false)
  886. {
  887. global $conf;
  888. if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
  889. $sql = 'SELECT f.rowid,f.facnumber,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc,f.amount,f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc, f.revenuestamp';
  890. $sql.= ', f.remise_percent, f.remise_absolue, f.remise';
  891. $sql.= ', f.datef as df, f.date_pointoftax';
  892. $sql.= ', f.date_lim_reglement as dlr';
  893. $sql.= ', f.datec as datec';
  894. $sql.= ', f.date_valid as datev';
  895. $sql.= ', f.tms as datem';
  896. $sql.= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf';
  897. $sql.= ', f.fk_facture_source';
  898. $sql.= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet, f.extraparams';
  899. $sql.= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
  900. $sql.= ', f.fk_account';
  901. $sql.= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
  902. $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
  903. $sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
  904. $sql.= ', f.fk_incoterms, f.location_incoterms';
  905. $sql.= ", i.libelle as libelle_incoterms";
  906. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f';
  907. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
  908. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
  909. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
  910. $sql.= ' WHERE f.entity = '.$conf->entity;
  911. if ($rowid) $sql.= " AND f.rowid=".$rowid;
  912. if ($ref) $sql.= " AND f.facnumber='".$this->db->escape($ref)."'";
  913. if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
  914. if ($ref_int) $sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'";
  915. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  916. $result = $this->db->query($sql);
  917. if ($result)
  918. {
  919. if ($this->db->num_rows($result))
  920. {
  921. $obj = $this->db->fetch_object($result);
  922. $this->id = $obj->rowid;
  923. $this->ref = $obj->facnumber;
  924. $this->ref_client = $obj->ref_client;
  925. $this->ref_ext = $obj->ref_ext;
  926. $this->ref_int = $obj->ref_int;
  927. $this->type = $obj->type;
  928. $this->date = $this->db->jdate($obj->df);
  929. $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
  930. $this->date_creation = $this->db->jdate($obj->datec);
  931. $this->date_validation = $this->db->jdate($obj->datev);
  932. $this->datem = $this->db->jdate($obj->datem);
  933. $this->remise_percent = $obj->remise_percent;
  934. $this->remise_absolue = $obj->remise_absolue;
  935. $this->total_ht = $obj->total;
  936. $this->total_tva = $obj->tva;
  937. $this->total_localtax1 = $obj->localtax1;
  938. $this->total_localtax2 = $obj->localtax2;
  939. $this->total_ttc = $obj->total_ttc;
  940. $this->revenuestamp = $obj->revenuestamp;
  941. $this->paye = $obj->paye;
  942. $this->close_code = $obj->close_code;
  943. $this->close_note = $obj->close_note;
  944. $this->socid = $obj->fk_soc;
  945. $this->statut = $obj->fk_statut;
  946. $this->date_lim_reglement = $this->db->jdate($obj->dlr);
  947. $this->mode_reglement_id = $obj->fk_mode_reglement;
  948. $this->mode_reglement_code = $obj->mode_reglement_code;
  949. $this->mode_reglement = $obj->mode_reglement_libelle;
  950. $this->cond_reglement_id = $obj->fk_cond_reglement;
  951. $this->cond_reglement_code = $obj->cond_reglement_code;
  952. $this->cond_reglement = $obj->cond_reglement_libelle;
  953. $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
  954. $this->fk_account = ($obj->fk_account>0)?$obj->fk_account:null;
  955. $this->fk_project = $obj->fk_projet;
  956. $this->fk_facture_source = $obj->fk_facture_source;
  957. $this->note = $obj->note_private; // deprecated
  958. $this->note_private = $obj->note_private;
  959. $this->note_public = $obj->note_public;
  960. $this->user_author = $obj->fk_user_author;
  961. $this->user_valid = $obj->fk_user_valid;
  962. $this->modelpdf = $obj->model_pdf;
  963. $this->situation_cycle_ref = $obj->situation_cycle_ref;
  964. $this->situation_counter = $obj->situation_counter;
  965. $this->situation_final = $obj->situation_final;
  966. $this->extraparams = (array) json_decode($obj->extraparams, true);
  967. //Incoterms
  968. $this->fk_incoterms = $obj->fk_incoterms;
  969. $this->location_incoterms = $obj->location_incoterms;
  970. $this->libelle_incoterms = $obj->libelle_incoterms;
  971. // Multicurrency
  972. $this->fk_multicurrency = $obj->fk_multicurrency;
  973. $this->multicurrency_code = $obj->multicurrency_code;
  974. $this->multicurrency_tx = $obj->multicurrency_tx;
  975. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  976. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  977. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  978. if ($this->type == self::TYPE_SITUATION && $fetch_situation)
  979. {
  980. $this->fetchPreviousNextSituationInvoice();
  981. }
  982. if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
  983. // Retrieve all extrafield for invoice
  984. // fetch optionals attributes and labels
  985. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  986. $extrafields=new ExtraFields($this->db);
  987. $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
  988. $this->fetch_optionals($this->id,$extralabels);
  989. /*
  990. * Lines
  991. */
  992. $this->lines = array();
  993. $result=$this->fetch_lines();
  994. if ($result < 0)
  995. {
  996. $this->error=$this->db->error();
  997. return -3;
  998. }
  999. return 1;
  1000. }
  1001. else
  1002. {
  1003. $this->error='Bill with id '.$rowid.' or ref '.$ref.' not found';
  1004. dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR);
  1005. return 0;
  1006. }
  1007. }
  1008. else
  1009. {
  1010. $this->error=$this->db->error();
  1011. return -1;
  1012. }
  1013. }
  1014. /**
  1015. * Load all detailed lines into this->lines
  1016. *
  1017. * @return int 1 if OK, < 0 if KO
  1018. */
  1019. function fetch_lines()
  1020. {
  1021. $this->lines=array();
  1022. $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.tva_tx, ';
  1023. $sql.= ' l.situation_percent, l.fk_prev_id,';
  1024. $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,';
  1025. $sql.= ' l.rang, l.special_code,';
  1026. $sql.= ' l.date_start as date_start, l.date_end as date_end,';
  1027. $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,';
  1028. $sql.= ' l.fk_unit,';
  1029. $sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
  1030. $sql.= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
  1031. $sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
  1032. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
  1033. $sql.= ' WHERE l.fk_facture = '.$this->id;
  1034. $sql.= ' ORDER BY l.rang, l.rowid';
  1035. dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
  1036. $result = $this->db->query($sql);
  1037. if ($result)
  1038. {
  1039. $num = $this->db->num_rows($result);
  1040. $i = 0;
  1041. while ($i < $num)
  1042. {
  1043. $objp = $this->db->fetch_object($result);
  1044. $line = new FactureLigne($this->db);
  1045. $line->id = $objp->rowid;
  1046. $line->rowid = $objp->rowid; // deprecated
  1047. $line->label = $objp->custom_label; // deprecated
  1048. $line->desc = $objp->description; // Description line
  1049. $line->description = $objp->description; // Description line
  1050. $line->product_type = $objp->product_type; // Type of line
  1051. $line->ref = $objp->product_ref; // Ref product
  1052. $line->product_ref = $objp->product_ref; // Ref product
  1053. $line->libelle = $objp->product_label; // TODO deprecated
  1054. $line->product_label = $objp->product_label; // Label product
  1055. $line->product_desc = $objp->product_desc; // Description product
  1056. $line->fk_product_type = $objp->fk_product_type; // Type of product
  1057. $line->qty = $objp->qty;
  1058. $line->subprice = $objp->subprice;
  1059. $line->tva_tx = $objp->tva_tx;
  1060. $line->localtax1_tx = $objp->localtax1_tx;
  1061. $line->localtax2_tx = $objp->localtax2_tx;
  1062. $line->localtax1_type = $objp->localtax1_type;
  1063. $line->localtax2_type = $objp->localtax2_type;
  1064. $line->remise_percent = $objp->remise_percent;
  1065. $line->fk_remise_except = $objp->fk_remise_except;
  1066. $line->fk_product = $objp->fk_product;
  1067. $line->date_start = $this->db->jdate($objp->date_start);
  1068. $line->date_end = $this->db->jdate($objp->date_end);
  1069. $line->date_start = $this->db->jdate($objp->date_start);
  1070. $line->date_end = $this->db->jdate($objp->date_end);
  1071. $line->info_bits = $objp->info_bits;
  1072. $line->total_ht = $objp->total_ht;
  1073. $line->total_tva = $objp->total_tva;
  1074. $line->total_localtax1 = $objp->total_localtax1;
  1075. $line->total_localtax2 = $objp->total_localtax2;
  1076. $line->total_ttc = $objp->total_ttc;
  1077. $line->code_ventilation = $objp->fk_code_ventilation;
  1078. $line->fk_fournprice = $objp->fk_fournprice;
  1079. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
  1080. $line->pa_ht = $marginInfos[0];
  1081. $line->marge_tx = $marginInfos[1];
  1082. $line->marque_tx = $marginInfos[2];
  1083. $line->rang = $objp->rang;
  1084. $line->special_code = $objp->special_code;
  1085. $line->fk_parent_line = $objp->fk_parent_line;
  1086. $line->situation_percent= $objp->situation_percent;
  1087. $line->fk_prev_id = $objp->fk_prev_id;
  1088. $line->fk_unit = $objp->fk_unit;
  1089. // Multicurrency
  1090. $line->fk_multicurrency = $objp->fk_multicurrency;
  1091. $line->multicurrency_code = $objp->multicurrency_code;
  1092. $line->multicurrency_subprice = $objp->multicurrency_subprice;
  1093. $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
  1094. $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
  1095. $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  1096. $this->lines[$i] = $line;
  1097. $i++;
  1098. }
  1099. $this->db->free($result);
  1100. return 1;
  1101. }
  1102. else
  1103. {
  1104. $this->error=$this->db->error();
  1105. return -3;
  1106. }
  1107. }
  1108. /**
  1109. * Fetch previous and next situations invoices
  1110. *
  1111. * @return void
  1112. */
  1113. function fetchPreviousNextSituationInvoice()
  1114. {
  1115. global $conf;
  1116. $this->tab_previous_situation_invoice = array();
  1117. $this->tab_next_situation_invoice = array();
  1118. $sql = 'SELECT rowid, situation_counter FROM '.MAIN_DB_PREFIX.'facture WHERE rowid <> '.$this->id.' AND entity = '.$conf->entity.' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref.' ORDER BY situation_counter ASC';
  1119. dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
  1120. $result = $this->db->query($sql);
  1121. if ($result && $this->db->num_rows($result) > 0)
  1122. {
  1123. while ($objp = $this->db->fetch_object($result))
  1124. {
  1125. $invoice = new Facture($this->db);
  1126. if ($invoice->fetch($objp->rowid) > 0)
  1127. {
  1128. if ($objp->situation_counter < $this->situation_counter) $this->tab_previous_situation_invoice[] = $invoice;
  1129. else $this->tab_next_situation_invoice[] = $invoice;
  1130. }
  1131. }
  1132. }
  1133. }
  1134. /**
  1135. * Update database
  1136. *
  1137. * @param User $user User that modify
  1138. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  1139. * @return int <0 if KO, >0 if OK
  1140. */
  1141. function update($user=null, $notrigger=0)
  1142. {
  1143. $error=0;
  1144. // Clean parameters
  1145. if (empty($this->type)) $this->type= self::TYPE_STANDARD;
  1146. if (isset($this->facnumber)) $this->facnumber=trim($this->ref);
  1147. if (isset($this->ref_client)) $this->ref_client=trim($this->ref_client);
  1148. if (isset($this->increment)) $this->increment=trim($this->increment);
  1149. if (isset($this->close_code)) $this->close_code=trim($this->close_code);
  1150. if (isset($this->close_note)) $this->close_note=trim($this->close_note);
  1151. if (isset($this->note) || isset($this->note_private)) $this->note=(isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
  1152. if (isset($this->note) || isset($this->note_private)) $this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note));
  1153. if (isset($this->note_public)) $this->note_public=trim($this->note_public);
  1154. if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf);
  1155. if (isset($this->import_key)) $this->import_key=trim($this->import_key);
  1156. if (empty($this->situation_cycle_ref)) {
  1157. $this->situation_cycle_ref = 'null';
  1158. }
  1159. if (empty($this->situation_counter)) {
  1160. $this->situation_counter = 'null';
  1161. }
  1162. if (empty($this->situation_final)) {
  1163. $this->situation_final = '0';
  1164. }
  1165. // Check parameters
  1166. // Put here code to add control on parameters values
  1167. // Update request
  1168. $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
  1169. $sql.= " facnumber=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
  1170. $sql.= " type=".(isset($this->type)?$this->type:"null").",";
  1171. $sql.= " ref_client=".(isset($this->ref_client)?"'".$this->db->escape($this->ref_client)."'":"null").",";
  1172. $sql.= " increment=".(isset($this->increment)?"'".$this->db->escape($this->increment)."'":"null").",";
  1173. $sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").",";
  1174. $sql.= " datec=".(strval($this->date_creation)!='' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
  1175. $sql.= " datef=".(strval($this->date)!='' ? "'".$this->db->idate($this->date)."'" : 'null').",";
  1176. $sql.= " date_pointoftax=".(strval($this->date_pointoftax)!='' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
  1177. $sql.= " date_valid=".(strval($this->date_validation)!='' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
  1178. $sql.= " paye=".(isset($this->paye)?$this->paye:"null").",";
  1179. $sql.= " remise_percent=".(isset($this->remise_percent)?$this->remise_percent:"null").",";
  1180. $sql.= " remise_absolue=".(isset($this->remise_absolue)?$this->remise_absolue:"null").",";
  1181. $sql.= " close_code=".(isset($this->close_code)?"'".$this->db->escape($this->close_code)."'":"null").",";
  1182. $sql.= " close_note=".(isset($this->close_note)?"'".$this->db->escape($this->close_note)."'":"null").",";
  1183. $sql.= " tva=".(isset($this->total_tva)?$this->total_tva:"null").",";
  1184. $sql.= " localtax1=".(isset($this->total_localtax1)?$this->total_localtax1:"null").",";
  1185. $sql.= " localtax2=".(isset($this->total_localtax2)?$this->total_localtax2:"null").",";
  1186. $sql.= " total=".(isset($this->total_ht)?$this->total_ht:"null").",";
  1187. $sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").",";
  1188. $sql.= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '')?$this->revenuestamp:"null").",";
  1189. $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
  1190. $sql.= " fk_user_author=".(isset($this->user_author)?$this->user_author:"null").",";
  1191. $sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
  1192. $sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->fk_facture_source:"null").",";
  1193. $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
  1194. $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
  1195. $sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null").",";
  1196. $sql.= " date_lim_reglement=".(strval($this->date_lim_reglement)!='' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
  1197. $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
  1198. $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
  1199. $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").",";
  1200. $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null");
  1201. $sql.= ", situation_cycle_ref=".$this->situation_cycle_ref;
  1202. $sql.= ", situation_counter=".$this->situation_counter;
  1203. $sql.= ", situation_final=".$this->situation_final;
  1204. $sql.= " WHERE rowid=".$this->id;
  1205. $this->db->begin();
  1206. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  1207. $resql = $this->db->query($sql);
  1208. if (! $resql) {
  1209. $error++; $this->errors[]="Error ".$this->db->lasterror();
  1210. }
  1211. if (! $error)
  1212. {
  1213. if (! $notrigger)
  1214. {
  1215. // Call trigger
  1216. $result=$this->call_trigger('BILL_MODIFY',$user);
  1217. if ($result < 0) $error++;
  1218. // End call triggers
  1219. }
  1220. }
  1221. // Commit or rollback
  1222. if ($error)
  1223. {
  1224. foreach($this->errors as $errmsg)
  1225. {
  1226. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  1227. $this->error.=($this->error?', '.$errmsg:$errmsg);
  1228. }
  1229. $this->db->rollback();
  1230. return -1*$error;
  1231. }
  1232. else
  1233. {
  1234. $this->db->commit();
  1235. return 1;
  1236. }
  1237. }
  1238. /**
  1239. * Add a discount line into invoice using an existing absolute discount
  1240. *
  1241. * @param int $idremise Id of absolute discount
  1242. * @return int >0 if OK, <0 if KO
  1243. */
  1244. function insert_discount($idremise)
  1245. {
  1246. global $langs;
  1247. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1248. include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  1249. $this->db->begin();
  1250. $remise=new DiscountAbsolute($this->db);
  1251. $result=$remise->fetch($idremise);
  1252. if ($result > 0)
  1253. {
  1254. if ($remise->fk_facture) // Protection against multiple submission
  1255. {
  1256. $this->error=$langs->trans("ErrorDiscountAlreadyUsed");
  1257. $this->db->rollback();
  1258. return -5;
  1259. }
  1260. $facligne=new FactureLigne($this->db);
  1261. $facligne->fk_facture=$this->id;
  1262. $facligne->fk_remise_except=$remise->id;
  1263. $facligne->desc=$remise->description; // Description ligne
  1264. $facligne->tva_tx=$remise->tva_tx;
  1265. $facligne->subprice=-$remise->amount_ht;
  1266. $facligne->fk_product=0; // Id produit predefini
  1267. $facligne->qty=1;
  1268. $facligne->remise_percent=0;
  1269. $facligne->rang=-1;
  1270. $facligne->info_bits=2;
  1271. $facligne->total_ht = -$remise->amount_ht;
  1272. $facligne->total_tva = -$remise->amount_tva;
  1273. $facligne->total_ttc = -$remise->amount_ttc;
  1274. $lineid=$facligne->insert();
  1275. if ($lineid > 0)
  1276. {
  1277. $result=$this->update_price(1);
  1278. if ($result > 0)
  1279. {
  1280. // Create linke between discount and invoice line
  1281. $result=$remise->link_to_invoice($lineid,0);
  1282. if ($result < 0)
  1283. {
  1284. $this->error=$remise->error;
  1285. $this->db->rollback();
  1286. return -4;
  1287. }
  1288. $this->db->commit();
  1289. return 1;
  1290. }
  1291. else
  1292. {
  1293. $this->error=$facligne->error;
  1294. $this->db->rollback();
  1295. return -1;
  1296. }
  1297. }
  1298. else
  1299. {
  1300. $this->error=$facligne->error;
  1301. $this->db->rollback();
  1302. return -2;
  1303. }
  1304. }
  1305. else
  1306. {
  1307. $this->db->rollback();
  1308. return -3;
  1309. }
  1310. }
  1311. /**
  1312. * Set customer ref
  1313. *
  1314. * @param string $ref_client Customer ref
  1315. * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers
  1316. * @return int <0 if KO, >0 if OK
  1317. */
  1318. function set_ref_client($ref_client, $notrigger=0)
  1319. {
  1320. $error=0;
  1321. $this->db->begin();
  1322. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  1323. if (empty($ref_client))
  1324. $sql .= ' SET ref_client = NULL';
  1325. else
  1326. $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
  1327. $sql .= ' WHERE rowid = '.$this->id;
  1328. dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
  1329. $resql=$this->db->query($sql);
  1330. if (!$resql)
  1331. {
  1332. $this->errors[]=$this->db->error();
  1333. $error++;
  1334. }
  1335. if (! $error)
  1336. {
  1337. $this->ref_client = $ref_client;
  1338. }
  1339. if (! $notrigger && empty($error))
  1340. {
  1341. // Call trigger
  1342. $result=$this->call_trigger('BILL_MODIFY',$user);
  1343. if ($result < 0) $error++;
  1344. // End call triggers
  1345. }
  1346. if (! $error)
  1347. {
  1348. $this->ref_client = $ref_client;
  1349. $this->db->commit();
  1350. return 1;
  1351. }
  1352. else
  1353. {
  1354. foreach($this->errors as $errmsg)
  1355. {
  1356. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  1357. $this->error.=($this->error?', '.$errmsg:$errmsg);
  1358. }
  1359. $this->db->rollback();
  1360. return -1*$error;
  1361. }
  1362. }
  1363. /**
  1364. * Delete invoice
  1365. *
  1366. * @param int $rowid Id of invoice to delete. If empty, we delete current instance of invoice
  1367. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1368. * @param int $idwarehouse Id warehouse to use for stock change.
  1369. * @return int <0 if KO, >0 if OK
  1370. */
  1371. function delete($rowid=0, $notrigger=0, $idwarehouse=-1)
  1372. {
  1373. global $user,$langs,$conf;
  1374. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1375. if (empty($rowid)) $rowid=$this->id;
  1376. dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG);
  1377. // TODO Test if there is at least one payment. If yes, refuse to delete.
  1378. $error=0;
  1379. $this->db->begin();
  1380. if (! $error && ! $notrigger)
  1381. {
  1382. // Call trigger
  1383. $result=$this->call_trigger('BILL_DELETE',$user);
  1384. if ($result < 0) $error++;
  1385. // End call triggers
  1386. }
  1387. // Removed extrafields
  1388. if (! $error) {
  1389. $result=$this->deleteExtraFields();
  1390. if ($result < 0)
  1391. {
  1392. $error++;
  1393. dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
  1394. }
  1395. }
  1396. if (! $error)
  1397. {
  1398. // Delete linked object
  1399. $res = $this->deleteObjectLinked();
  1400. if ($res < 0) $error++;
  1401. }
  1402. if (! $error)
  1403. {
  1404. // If invoice was converted into a discount not yet consumed, we remove discount
  1405. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
  1406. $sql.= ' WHERE fk_facture_source = '.$rowid;
  1407. $sql.= ' AND fk_facture_line IS NULL';
  1408. $resql=$this->db->query($sql);
  1409. // If invoice has consumned discounts
  1410. $this->fetch_lines();
  1411. $list_rowid_det=array();
  1412. foreach($this->lines as $key => $invoiceline)
  1413. {
  1414. $list_rowid_det[]=$invoiceline->rowid;
  1415. }
  1416. // Consumned discounts are freed
  1417. if (count($list_rowid_det))
  1418. {
  1419. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  1420. $sql.= ' SET fk_facture = NULL, fk_facture_line = NULL';
  1421. $sql.= ' WHERE fk_facture_line IN ('.join(',',$list_rowid_det).')';
  1422. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1423. if (! $this->db->query($sql))
  1424. {
  1425. $this->error=$this->db->error()." sql=".$sql;
  1426. $this->db->rollback();
  1427. return -5;
  1428. }
  1429. }
  1430. // If we decrement stock on invoice validation, we increment
  1431. if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse!=-1)
  1432. {
  1433. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1434. $langs->load("agenda");
  1435. $num=count($this->lines);
  1436. for ($i = 0; $i < $num; $i++)
  1437. {
  1438. if ($this->lines[$i]->fk_product > 0)
  1439. {
  1440. $mouvP = new MouvementStock($this->db);
  1441. $mouvP->origin = &$this;
  1442. // We decrease stock for product
  1443. if ($this->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr",$this->ref));
  1444. else $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
  1445. }
  1446. }
  1447. }
  1448. // Delete invoice line
  1449. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.$rowid;
  1450. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1451. if ($this->db->query($sql) && $this->delete_linked_contact())
  1452. {
  1453. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.$rowid;
  1454. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1455. $resql=$this->db->query($sql);
  1456. if ($resql)
  1457. {
  1458. // On efface le repertoire de pdf provisoire
  1459. $ref = dol_sanitizeFileName($this->ref);
  1460. if ($conf->facture->dir_output && !empty($this->ref))
  1461. {
  1462. $dir = $conf->facture->dir_output . "/" . $ref;
  1463. $file = $conf->facture->dir_output . "/" . $ref . "/" . $ref . ".pdf";
  1464. if (file_exists($file)) // We must delete all files before deleting directory
  1465. {
  1466. $ret=dol_delete_preview($this);
  1467. if (! dol_delete_file($file,0,0,0,$this)) // For triggers
  1468. {
  1469. $this->error=$langs->trans("ErrorCanNotDeleteFile",$file);
  1470. $this->db->rollback();
  1471. return 0;
  1472. }
  1473. }
  1474. if (file_exists($dir))
  1475. {
  1476. if (! dol_delete_dir_recursive($dir)) // For remove dir and meta
  1477. {
  1478. $this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
  1479. $this->db->rollback();
  1480. return 0;
  1481. }
  1482. }
  1483. }
  1484. $this->db->commit();
  1485. return 1;
  1486. }
  1487. else
  1488. {
  1489. $this->error=$this->db->lasterror()." sql=".$sql;
  1490. $this->db->rollback();
  1491. return -6;
  1492. }
  1493. }
  1494. else
  1495. {
  1496. $this->error=$this->db->lasterror()." sql=".$sql;
  1497. $this->db->rollback();
  1498. return -4;
  1499. }
  1500. }
  1501. else
  1502. {
  1503. $this->db->rollback();
  1504. return -2;
  1505. }
  1506. }
  1507. /**
  1508. * Tag la facture comme paye completement (si close_code non renseigne) => this->fk_statut=2, this->paye=1
  1509. * ou partiellement (si close_code renseigne) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0
  1510. *
  1511. * @param User $user Objet utilisateur qui modifie
  1512. * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple)
  1513. * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple)
  1514. * @return int <0 if KO, >0 if OK
  1515. */
  1516. function set_paid($user,$close_code='',$close_note='')
  1517. {
  1518. $error=0;
  1519. if ($this->paye != 1)
  1520. {
  1521. $this->db->begin();
  1522. dol_syslog(get_class($this)."::set_paid rowid=".$this->id, LOG_DEBUG);
  1523. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
  1524. $sql.= ' fk_statut='.self::STATUS_CLOSED;
  1525. if (! $close_code) $sql.= ', paye=1';
  1526. if ($close_code) $sql.= ", close_code='".$this->db->escape($close_code)."'";
  1527. if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'";
  1528. $sql.= ' WHERE rowid = '.$this->id;
  1529. dol_syslog(get_class($this)."::set_paid", LOG_DEBUG);
  1530. $resql = $this->db->query($sql);
  1531. if ($resql)
  1532. {
  1533. // Call trigger
  1534. $result=$this->call_trigger('BILL_PAYED',$user);
  1535. if ($result < 0) $error++;
  1536. // End call triggers
  1537. }
  1538. else
  1539. {
  1540. $error++;
  1541. $this->error=$this->db->lasterror();
  1542. }
  1543. if (! $error)
  1544. {
  1545. $this->db->commit();
  1546. return 1;
  1547. }
  1548. else
  1549. {
  1550. $this->db->rollback();
  1551. return -1;
  1552. }
  1553. }
  1554. else
  1555. {
  1556. return 0;
  1557. }
  1558. }
  1559. /**
  1560. * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
  1561. * Fonction utilisee quand un paiement prelevement est refuse,
  1562. * ou quand une facture annulee et reouverte.
  1563. *
  1564. * @param User $user Object user that change status
  1565. * @return int <0 if KO, >0 if OK
  1566. */
  1567. function set_unpaid($user)
  1568. {
  1569. $error=0;
  1570. $this->db->begin();
  1571. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  1572. $sql.= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null';
  1573. $sql.= ' WHERE rowid = '.$this->id;
  1574. dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
  1575. $resql = $this->db->query($sql);
  1576. if ($resql)
  1577. {
  1578. // Call trigger
  1579. $result=$this->call_trigger('BILL_UNPAYED',$user);
  1580. if ($result < 0) $error++;
  1581. // End call triggers
  1582. }
  1583. else
  1584. {
  1585. $error++;
  1586. $this->error=$this->db->error();
  1587. dol_print_error($this->db);
  1588. }
  1589. if (! $error)
  1590. {
  1591. $this->db->commit();
  1592. return 1;
  1593. }
  1594. else
  1595. {
  1596. $this->db->rollback();
  1597. return -1;
  1598. }
  1599. }
  1600. /**
  1601. * Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never received) + call trigger BILL_CANCEL
  1602. * Warning, if option to decrease stock on invoice was set, this function does not change stock (it might be a cancel because
  1603. * of no payment even if merchandises were sent).
  1604. *
  1605. * @param User $user Object user making change
  1606. * @param string $close_code Code de fermeture
  1607. * @param string $close_note Comment
  1608. * @return int <0 if KO, >0 if OK
  1609. */
  1610. function set_canceled($user,$close_code='',$close_note='')
  1611. {
  1612. dol_syslog(get_class($this)."::set_canceled rowid=".$this->id, LOG_DEBUG);
  1613. $this->db->begin();
  1614. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
  1615. $sql.= ' fk_statut='.self::STATUS_ABANDONED;
  1616. if ($close_code) $sql.= ", close_code='".$this->db->escape($close_code)."'";
  1617. if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'";
  1618. $sql.= ' WHERE rowid = '.$this->id;
  1619. $resql = $this->db->query($sql);
  1620. if ($resql)
  1621. {
  1622. // On desaffecte de la facture les remises liees
  1623. // car elles n'ont pas ete utilisees vu que la facture est abandonnee.
  1624. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  1625. $sql.= ' SET fk_facture = NULL';
  1626. $sql.= ' WHERE fk_facture = '.$this->id;
  1627. $resql=$this->db->query($sql);
  1628. if ($resql)
  1629. {
  1630. // Call trigger
  1631. $result=$this->call_trigger('BILL_CANCEL',$user);
  1632. if ($result < 0)
  1633. {
  1634. $this->db->rollback();
  1635. return -1;
  1636. }
  1637. // End call triggers
  1638. $this->db->commit();
  1639. return 1;
  1640. }
  1641. else
  1642. {
  1643. $this->error=$this->db->error()." sql=".$sql;
  1644. $this->db->rollback();
  1645. return -1;
  1646. }
  1647. }
  1648. else
  1649. {
  1650. $this->error=$this->db->error()." sql=".$sql;
  1651. $this->db->rollback();
  1652. return -2;
  1653. }
  1654. }
  1655. /**
  1656. * Tag invoice as validated + call trigger BILL_VALIDATE
  1657. * Object must have lines loaded with fetch_lines
  1658. *
  1659. * @param User $user Object user that validate
  1660. * @param string $force_number Reference to force on invoice
  1661. * @param int $idwarehouse Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease)
  1662. * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers
  1663. * @return int <0 if KO, >0 if OK
  1664. */
  1665. function validate($user, $force_number='', $idwarehouse=0, $notrigger=0)
  1666. {
  1667. global $conf,$langs;
  1668. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1669. $now=dol_now();
  1670. $error=0;
  1671. dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
  1672. // Check parameters
  1673. if (! $this->brouillon)
  1674. {
  1675. dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
  1676. return 0;
  1677. }
  1678. if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
  1679. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate)))
  1680. {
  1681. $this->error='Permission denied';
  1682. dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
  1683. return -1;
  1684. }
  1685. $this->db->begin();
  1686. $this->fetch_thirdparty();
  1687. $this->fetch_lines();
  1688. // Check parameters
  1689. if ($this->type == self::TYPE_REPLACEMENT) // si facture de remplacement
  1690. {
  1691. // Controle que facture source connue
  1692. if ($this->fk_facture_source <= 0)
  1693. {
  1694. $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("InvoiceReplacement"));
  1695. $this->db->rollback();
  1696. return -10;
  1697. }
  1698. // Charge la facture source a remplacer
  1699. $facreplaced=new Facture($this->db);
  1700. $result=$facreplaced->fetch($this->fk_facture_source);
  1701. if ($result <= 0)
  1702. {
  1703. $this->error=$langs->trans("ErrorBadInvoice");
  1704. $this->db->rollback();
  1705. return -11;
  1706. }
  1707. // Controle que facture source non deja remplacee par une autre
  1708. $idreplacement=$facreplaced->getIdReplacingInvoice('validated');
  1709. if ($idreplacement && $idreplacement != $this->id)
  1710. {
  1711. $facreplacement=new Facture($this->db);
  1712. $facreplacement->fetch($idreplacement);
  1713. $this->error=$langs->trans("ErrorInvoiceAlreadyReplaced",$facreplaced->ref,$facreplacement->ref);
  1714. $this->db->rollback();
  1715. return -12;
  1716. }
  1717. $result=$facreplaced->set_canceled($user,'replaced','');
  1718. if ($result < 0)
  1719. {
  1720. $this->error=$facreplaced->error;
  1721. $this->db->rollback();
  1722. return -13;
  1723. }
  1724. }
  1725. // Define new ref
  1726. if ($force_number)
  1727. {
  1728. $num = $force_number;
  1729. }
  1730. else if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
  1731. {
  1732. if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date
  1733. {
  1734. $this->date=dol_now();
  1735. $this->date_lim_reglement=$this->calculate_date_lim_reglement();
  1736. }
  1737. $num = $this->getNextNumRef($this->thirdparty);
  1738. }
  1739. else
  1740. {
  1741. $num = $this->ref;
  1742. }
  1743. $this->newref = $num;
  1744. if ($num)
  1745. {
  1746. $this->update_price(1);
  1747. // Validate
  1748. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  1749. $sql.= " SET facnumber='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
  1750. if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date
  1751. {
  1752. $sql.= ", datef='".$this->db->idate($this->date)."'";
  1753. $sql.= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
  1754. }
  1755. $sql.= ' WHERE rowid = '.$this->id;
  1756. dol_syslog(get_class($this)."::validate", LOG_DEBUG);
  1757. $resql=$this->db->query($sql);
  1758. if (! $resql)
  1759. {
  1760. dol_print_error($this->db);
  1761. $error++;
  1762. }
  1763. // On verifie si la facture etait une provisoire
  1764. if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref)))
  1765. {
  1766. // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne
  1767. }
  1768. if (! $error)
  1769. {
  1770. // Define third party as a customer
  1771. $result=$this->thirdparty->set_as_client();
  1772. // Si active on decremente le produit principal et ses composants a la validation de facture
  1773. if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0)
  1774. {
  1775. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1776. $langs->load("agenda");
  1777. // Loop on each line
  1778. $cpt=count($this->lines);
  1779. for ($i = 0; $i < $cpt; $i++)
  1780. {
  1781. if ($this->lines[$i]->fk_product > 0)
  1782. {
  1783. $mouvP = new MouvementStock($this->db);
  1784. $mouvP->origin = &$this;
  1785. // We decrease stock for product
  1786. if ($this->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr",$num));
  1787. else $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr",$num));
  1788. if ($result < 0) {
  1789. $error++;
  1790. }
  1791. }
  1792. }
  1793. }
  1794. }
  1795. // Trigger calls
  1796. if (! $error && ! $notrigger)
  1797. {
  1798. // Call trigger
  1799. $result=$this->call_trigger('BILL_VALIDATE',$user);
  1800. if ($result < 0) $error++;
  1801. // End call triggers
  1802. }
  1803. if (! $error)
  1804. {
  1805. $this->oldref = $this->ref;
  1806. // Rename directory if dir was a temporary ref
  1807. if (preg_match('/^[\(]?PROV/i', $this->ref))
  1808. {
  1809. // Rename of object directory ($this->ref = old ref, $num = new ref)
  1810. // to not lose the linked files
  1811. $oldref = dol_sanitizeFileName($this->ref);
  1812. $newref = dol_sanitizeFileName($num);
  1813. $dirsource = $conf->facture->dir_output.'/'.$oldref;
  1814. $dirdest = $conf->facture->dir_output.'/'.$newref;
  1815. if (file_exists($dirsource))
  1816. {
  1817. dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
  1818. if (@rename($dirsource, $dirdest))
  1819. {
  1820. dol_syslog("Rename ok");
  1821. // Rename docs starting with $oldref with $newref
  1822. $listoffiles=dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
  1823. foreach($listoffiles as $fileentry)
  1824. {
  1825. $dirsource=$fileentry['name'];
  1826. $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
  1827. $dirsource=$fileentry['path'].'/'.$dirsource;
  1828. $dirdest=$fileentry['path'].'/'.$dirdest;
  1829. @rename($dirsource, $dirdest);
  1830. }
  1831. }
  1832. }
  1833. }
  1834. }
  1835. if (! $error && !$this->is_last_in_cycle())
  1836. {
  1837. if (! $this->updatePriceNextInvoice($langs))
  1838. {
  1839. $error++;
  1840. }
  1841. }
  1842. // Set new ref and define current statut
  1843. if (! $error)
  1844. {
  1845. $this->ref = $num;
  1846. $this->facnumber=$num;
  1847. $this->statut= self::STATUS_VALIDATED;
  1848. $this->brouillon=0;
  1849. $this->date_validation=$now;
  1850. $i = 0;
  1851. if (!empty($conf->global->INVOICE_USE_SITUATION))
  1852. {
  1853. $final = True;
  1854. while ($i < count($this->lines) && $final == True) {
  1855. $final = ($this->lines[$i]->situation_percent == 100);
  1856. $i++;
  1857. }
  1858. if ($final) {
  1859. $this->setFinal($user);
  1860. }
  1861. }
  1862. }
  1863. }
  1864. else
  1865. {
  1866. $error++;
  1867. }
  1868. if (! $error)
  1869. {
  1870. $this->db->commit();
  1871. return 1;
  1872. }
  1873. else
  1874. {
  1875. $this->db->rollback();
  1876. return -1;
  1877. }
  1878. }
  1879. /**
  1880. * Update price of next invoice
  1881. *
  1882. * @param Translate $langs Translate object
  1883. * @return bool false if KO, true if OK
  1884. */
  1885. function updatePriceNextInvoice(&$langs)
  1886. {
  1887. foreach ($this->tab_next_situation_invoice as $next_invoice)
  1888. {
  1889. $is_last = $next_invoice->is_last_in_cycle();
  1890. if ($next_invoice->brouillon && $is_last != 1)
  1891. {
  1892. $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
  1893. return false;
  1894. }
  1895. $next_invoice->brouillon = 1;
  1896. foreach ($next_invoice->lines as $line)
  1897. {
  1898. $result = $next_invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent,
  1899. $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type,
  1900. $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent,
  1901. $line->fk_unit);
  1902. if ($result < 0)
  1903. {
  1904. $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
  1905. return false;
  1906. }
  1907. }
  1908. break; // Only the next invoice and not each next invoice
  1909. }
  1910. return true;
  1911. }
  1912. /**
  1913. * Set draft status
  1914. *
  1915. * @param User $user Object user that modify
  1916. * @param int $idwarehouse Id warehouse to use for stock change.
  1917. * @return int <0 if KO, >0 if OK
  1918. */
  1919. function set_draft($user,$idwarehouse=-1)
  1920. {
  1921. global $conf,$langs;
  1922. $error=0;
  1923. if ($this->statut == self::STATUS_DRAFT)
  1924. {
  1925. dol_syslog(get_class($this)."::set_draft already draft status", LOG_WARNING);
  1926. return 0;
  1927. }
  1928. $this->db->begin();
  1929. $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
  1930. $sql.= " SET fk_statut = ".self::STATUS_DRAFT;
  1931. $sql.= " WHERE rowid = ".$this->id;
  1932. dol_syslog(get_class($this)."::set_draft", LOG_DEBUG);
  1933. $result=$this->db->query($sql);
  1934. if ($result)
  1935. {
  1936. // Si on decremente le produit principal et ses composants a la validation de facture, on réincrement
  1937. if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL))
  1938. {
  1939. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1940. $langs->load("agenda");
  1941. $num=count($this->lines);
  1942. for ($i = 0; $i < $num; $i++)
  1943. {
  1944. if ($this->lines[$i]->fk_product > 0)
  1945. {
  1946. $mouvP = new MouvementStock($this->db);
  1947. $mouvP->origin = &$this;
  1948. // We decrease stock for product
  1949. if ($this->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
  1950. else $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
  1951. }
  1952. }
  1953. }
  1954. if ($error == 0)
  1955. {
  1956. $old_statut=$this->statut;
  1957. $this->brouillon = 1;
  1958. $this->statut = self::STATUS_DRAFT;
  1959. // Call trigger
  1960. $result=$this->call_trigger('BILL_UNVALIDATE',$user);
  1961. if ($result < 0)
  1962. {
  1963. $error++;
  1964. $this->statut=$old_statut;
  1965. $this->brouillon=0;
  1966. }
  1967. // End call triggers
  1968. } else {
  1969. $this->db->rollback();
  1970. return -1;
  1971. }
  1972. if ($error == 0)
  1973. {
  1974. $this->db->commit();
  1975. return 1;
  1976. }
  1977. else
  1978. {
  1979. $this->db->rollback();
  1980. return -1;
  1981. }
  1982. }
  1983. else
  1984. {
  1985. $this->error=$this->db->error();
  1986. $this->db->rollback();
  1987. return -1;
  1988. }
  1989. }
  1990. /**
  1991. * Add an invoice line into database (linked to product/service or not).
  1992. * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
  1993. * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
  1994. * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,produit)
  1995. * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue)
  1996. *
  1997. * @param string $desc Description of line
  1998. * @param double $pu_ht Unit price without tax (> 0 even for credit note)
  1999. * @param double $qty Quantity
  2000. * @param double $txtva Force vat rate, -1 for auto
  2001. * @param double $txlocaltax1 Local tax 1 rate (deprecated)
  2002. * @param double $txlocaltax2 Local tax 2 rate (deprecated)
  2003. * @param int $fk_product Id of predefined product/service
  2004. * @param double $remise_percent Percent of discount on line
  2005. * @param int $date_start Date start of service
  2006. * @param int $date_end Date end of service
  2007. * @param int $ventil Code of dispatching into accountancy
  2008. * @param int $info_bits Bits de type de lignes
  2009. * @param int $fk_remise_except Id discount used
  2010. * @param string $price_base_type 'HT' or 'TTC'
  2011. * @param double $pu_ttc Unit price with tax (> 0 even for credit note)
  2012. * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
  2013. * @param int $rang Position of line
  2014. * @param int $special_code Special code (also used by externals modules!)
  2015. * @param string $origin 'order', ...
  2016. * @param int $origin_id Id of origin object
  2017. * @param int $fk_parent_line Id of parent line
  2018. * @param int $fk_fournprice Supplier price id (to calculate margin) or ''
  2019. * @param int $pa_ht Buying price of line (to calculate margin) or ''
  2020. * @param string $label Label of the line (deprecated, do not use)
  2021. * @param array $array_options extrafields array
  2022. * @param int $situation_percent Situation advance percentage
  2023. * @param int $fk_prev_id Previous situation line id reference
  2024. * @param string $fk_unit Code of the unit to use. Null to use the default one
  2025. * @return int <0 if KO, Id of line if OK
  2026. */
  2027. function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id='', $fk_unit = null)
  2028. {
  2029. // Deprecation warning
  2030. if ($label) {
  2031. dol_syslog(__METHOD__ . ": using line label is deprecated", LOG_WARNING);
  2032. }
  2033. global $mysoc, $conf, $langs;
  2034. dol_syslog(get_class($this)."::addline facid=$this->id,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product,remise_percent=$remise_percent,date_start=$date_start,date_end=$date_end,ventil=$ventil,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type, fk_unit=$fk_unit", LOG_DEBUG);
  2035. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2036. // Clean parameters
  2037. if (empty($remise_percent)) $remise_percent=0;
  2038. if (empty($qty)) $qty=0;
  2039. if (empty($info_bits)) $info_bits=0;
  2040. if (empty($rang)) $rang=0;
  2041. if (empty($ventil)) $ventil=0;
  2042. if (empty($txtva)) $txtva=0;
  2043. if (empty($txlocaltax1)) $txlocaltax1=0;
  2044. if (empty($txlocaltax2)) $txlocaltax2=0;
  2045. if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
  2046. if (empty($fk_prev_id)) $fk_prev_id = 'null';
  2047. if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
  2048. $remise_percent=price2num($remise_percent);
  2049. $qty=price2num($qty);
  2050. $pu_ht=price2num($pu_ht);
  2051. $pu_ttc=price2num($pu_ttc);
  2052. $pa_ht=price2num($pa_ht);
  2053. $txtva=price2num($txtva);
  2054. $txlocaltax1=price2num($txlocaltax1);
  2055. $txlocaltax2=price2num($txlocaltax2);
  2056. if ($price_base_type=='HT')
  2057. {
  2058. $pu=$pu_ht;
  2059. }
  2060. else
  2061. {
  2062. $pu=$pu_ttc;
  2063. }
  2064. // Check parameters
  2065. if ($type < 0) return -1;
  2066. if (! empty($this->brouillon))
  2067. {
  2068. $this->db->begin();
  2069. $product_type=$type;
  2070. if (!empty($fk_product))
  2071. {
  2072. $product=new Product($this->db);
  2073. $result=$product->fetch($fk_product);
  2074. $product_type=$product->type;
  2075. if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
  2076. $langs->load("errors");
  2077. $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
  2078. $this->db->rollback();
  2079. return -3;
  2080. }
  2081. }
  2082. // Calcul du total TTC et de la TVA pour la ligne a partir de
  2083. // qty, pu, remise_percent et txtva
  2084. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  2085. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  2086. $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc);
  2087. $txtva = preg_replace('/\s*\(.*\)/','',$txtva); // Remove code into vatrate.
  2088. $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);
  2089. $total_ht = $tabprice[0];
  2090. $total_tva = $tabprice[1];
  2091. $total_ttc = $tabprice[2];
  2092. $total_localtax1 = $tabprice[9];
  2093. $total_localtax2 = $tabprice[10];
  2094. $pu_ht = $tabprice[3];
  2095. // MultiCurrency
  2096. $multicurrency_total_ht = $tabprice[16];
  2097. $multicurrency_total_tva = $tabprice[17];
  2098. $multicurrency_total_ttc = $tabprice[18];
  2099. // Rank to use
  2100. $rangtouse = $rang;
  2101. if ($rangtouse == -1)
  2102. {
  2103. $rangmax = $this->line_max($fk_parent_line);
  2104. $rangtouse = $rangmax + 1;
  2105. }
  2106. // Insert line
  2107. $this->line=new FactureLigne($this->db);
  2108. $this->line->context = $this->context;
  2109. $this->line->fk_facture=$this->id;
  2110. $this->line->label=$label; // deprecated
  2111. $this->line->desc=$desc;
  2112. $this->line->qty= ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty); // For credit note, quantity is always positive and unit price negative
  2113. $this->line->subprice= ($this->type==self::TYPE_CREDIT_NOTE?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise
  2114. $this->line->tva_tx=$txtva;
  2115. $this->line->localtax1_tx=$txlocaltax1;
  2116. $this->line->localtax2_tx=$txlocaltax2;
  2117. $this->line->localtax1_type = $localtaxes_type[0];
  2118. $this->line->localtax2_type = $localtaxes_type[2];
  2119. $this->line->total_ht= (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ht):$total_ht); // For credit note and if qty is negative, total is negative
  2120. $this->line->total_ttc= (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ttc):$total_ttc); // For credit note and if qty is negative, total is negative
  2121. $this->line->total_tva= (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_tva):$total_tva); // For credit note and if qty is negative, total is negative
  2122. $this->line->total_localtax1=(($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_localtax1):$total_localtax1); // For credit note and if qty is negative, total is negative
  2123. $this->line->total_localtax2=(($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_localtax2):$total_localtax2); // For credit note and if qty is negative, total is negative
  2124. $this->line->fk_product=$fk_product;
  2125. $this->line->product_type=$product_type;
  2126. $this->line->remise_percent=$remise_percent;
  2127. $this->line->date_start=$date_start;
  2128. $this->line->date_end=$date_end;
  2129. $this->line->ventil=$ventil;
  2130. $this->line->rang=$rangtouse;
  2131. $this->line->info_bits=$info_bits;
  2132. $this->line->fk_remise_except=$fk_remise_except;
  2133. $this->line->special_code=$special_code;
  2134. $this->line->fk_parent_line=$fk_parent_line;
  2135. $this->line->origin=$origin;
  2136. $this->line->origin_id=$origin_id;
  2137. $this->line->situation_percent = $situation_percent;
  2138. $this->line->fk_prev_id = $fk_prev_id;
  2139. $this->line->fk_unit=$fk_unit;
  2140. // infos marge
  2141. $this->line->fk_fournprice = $fk_fournprice;
  2142. $this->line->pa_ht = $pa_ht;
  2143. // Multicurrency
  2144. $this->line->fk_multicurrency = $this->fk_multicurrency;
  2145. $this->line->multicurrency_code = $this->multicurrency_code;
  2146. $this->line->multicurrency_subprice = price2num($this->line->subprice * $this->multicurrency_tx);
  2147. $this->line->multicurrency_total_ht = $multicurrency_total_ht;
  2148. $this->line->multicurrency_total_tva = $multicurrency_total_tva;
  2149. $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
  2150. if (is_array($array_options) && count($array_options)>0) {
  2151. $this->line->array_options=$array_options;
  2152. }
  2153. $result=$this->line->insert();
  2154. if ($result > 0)
  2155. {
  2156. // Reorder if child line
  2157. if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
  2158. // Mise a jour informations denormalisees au niveau de la facture meme
  2159. $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.
  2160. if ($result > 0)
  2161. {
  2162. $this->db->commit();
  2163. return $this->line->rowid;
  2164. }
  2165. else
  2166. {
  2167. $this->error=$this->db->error();
  2168. $this->db->rollback();
  2169. return -1;
  2170. }
  2171. }
  2172. else
  2173. {
  2174. $this->error=$this->line->error;
  2175. $this->db->rollback();
  2176. return -2;
  2177. }
  2178. }
  2179. }
  2180. /**
  2181. * Update a detail line
  2182. *
  2183. * @param int $rowid Id of line to update
  2184. * @param string $desc Description of line
  2185. * @param double $pu Prix unitaire (HT ou TTC selon price_base_type) (> 0 even for credit note lines)
  2186. * @param double $qty Quantity
  2187. * @param double $remise_percent Pourcentage de remise de la ligne
  2188. * @param int $date_start Date de debut de validite du service
  2189. * @param int $date_end Date de fin de validite du service
  2190. * @param double $txtva VAT Rate
  2191. * @param double $txlocaltax1 Local tax 1 rate
  2192. * @param double $txlocaltax2 Local tax 2 rate
  2193. * @param string $price_base_type HT or TTC
  2194. * @param int $info_bits Miscellaneous informations
  2195. * @param int $type Type of line (0=product, 1=service)
  2196. * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines).
  2197. * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules)
  2198. * @param int $fk_fournprice Id of origin supplier price
  2199. * @param int $pa_ht Price (without tax) of product when it was bought
  2200. * @param string $label Label of the line (deprecated, do not use)
  2201. * @param int $special_code Special code (also used by externals modules!)
  2202. * @param array $array_options extrafields array
  2203. * @param int $situation_percent Situation advance percentage
  2204. * @param string $fk_unit Code of the unit to use. Null to use the default one
  2205. * @return int < 0 if KO, > 0 if OK
  2206. */
  2207. 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=0, $fk_unit = null)
  2208. {
  2209. global $conf,$user;
  2210. // Deprecation warning
  2211. if ($label) {
  2212. dol_syslog(__METHOD__ . ": using line label is deprecated", LOG_WARNING);
  2213. }
  2214. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2215. global $mysoc,$langs;
  2216. 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", LOG_DEBUG);
  2217. if ($this->brouillon)
  2218. {
  2219. if (!$this->is_last_in_cycle() && empty($this->error))
  2220. {
  2221. if (!$this->checkProgressLine($rowid, $situation_percent))
  2222. {
  2223. if (!$this->error) $this->error=$langs->trans('invoiceLineProgressError');
  2224. return -3;
  2225. }
  2226. }
  2227. $this->db->begin();
  2228. // Clean parameters
  2229. if (empty($qty)) $qty=0;
  2230. if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
  2231. if (empty($special_code) || $special_code == 3) $special_code=0;
  2232. if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
  2233. $remise_percent = price2num($remise_percent);
  2234. $qty = price2num($qty);
  2235. $pu = price2num($pu);
  2236. $pa_ht = price2num($pa_ht);
  2237. $txtva = price2num($txtva);
  2238. $txlocaltax1 = price2num($txlocaltax1);
  2239. $txlocaltax2 = price2num($txlocaltax2);
  2240. // Check parameters
  2241. if ($type < 0) return -1;
  2242. // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
  2243. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  2244. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  2245. $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc);
  2246. $txtva = preg_replace('/\s*\(.*\)/','',$txtva); // Remove code into vatrate.
  2247. $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);
  2248. $total_ht = $tabprice[0];
  2249. $total_tva = $tabprice[1];
  2250. $total_ttc = $tabprice[2];
  2251. $total_localtax1=$tabprice[9];
  2252. $total_localtax2=$tabprice[10];
  2253. $pu_ht = $tabprice[3];
  2254. $pu_tva = $tabprice[4];
  2255. $pu_ttc = $tabprice[5];
  2256. // MultiCurrency
  2257. $multicurrency_total_ht = $tabprice[16];
  2258. $multicurrency_total_tva = $tabprice[17];
  2259. $multicurrency_total_ttc = $tabprice[18];
  2260. // Old properties: $price, $remise (deprecated)
  2261. $price = $pu;
  2262. $remise = 0;
  2263. if ($remise_percent > 0)
  2264. {
  2265. $remise = round(($pu * $remise_percent / 100),2);
  2266. $price = ($pu - $remise);
  2267. }
  2268. $price = price2num($price);
  2269. //Fetch current line from the database and then clone the object and set it in $oldline property
  2270. $line = new FactureLigne($this->db);
  2271. $line->fetch($rowid);
  2272. if (!empty($line->fk_product))
  2273. {
  2274. $product=new Product($this->db);
  2275. $result=$product->fetch($line->fk_product);
  2276. $product_type=$product->type;
  2277. if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
  2278. $langs->load("errors");
  2279. $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
  2280. $this->db->rollback();
  2281. return -3;
  2282. }
  2283. }
  2284. $staticline = clone $line;
  2285. $line->oldline = $staticline;
  2286. $this->line = $line;
  2287. $this->line->context = $this->context;
  2288. // Reorder if fk_parent_line change
  2289. if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
  2290. {
  2291. $rangmax = $this->line_max($fk_parent_line);
  2292. $this->line->rang = $rangmax + 1;
  2293. }
  2294. $this->line->rowid = $rowid;
  2295. $this->line->label = $label;
  2296. $this->line->desc = $desc;
  2297. $this->line->qty = ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty); // For credit note, quantity is always positive and unit price negative
  2298. $this->line->tva_tx = $txtva;
  2299. $this->line->localtax1_tx = $txlocaltax1;
  2300. $this->line->localtax2_tx = $txlocaltax2;
  2301. $this->line->localtax1_type = $localtaxes_type[0];
  2302. $this->line->localtax2_type = $localtaxes_type[2];
  2303. $this->line->remise_percent = $remise_percent;
  2304. $this->line->subprice = ($this->type==2?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise
  2305. $this->line->date_start = $date_start;
  2306. $this->line->date_end = $date_end;
  2307. $this->line->total_ht = (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ht):$total_ht); // For credit note and if qty is negative, total is negative
  2308. $this->line->total_tva = (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_tva):$total_tva);
  2309. $this->line->total_localtax1 = $total_localtax1;
  2310. $this->line->total_localtax2 = $total_localtax2;
  2311. $this->line->total_ttc = (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ttc):$total_ttc);
  2312. $this->line->info_bits = $info_bits;
  2313. $this->line->special_code = $special_code;
  2314. $this->line->product_type = $type;
  2315. $this->line->fk_parent_line = $fk_parent_line;
  2316. $this->line->skip_update_total = $skip_update_total;
  2317. $this->line->situation_percent = $situation_percent;
  2318. $this->line->fk_unit = $fk_unit;
  2319. $this->line->fk_fournprice = $fk_fournprice;
  2320. $this->line->pa_ht = $pa_ht;
  2321. // Multicurrency
  2322. $this->line->multicurrency_subprice = price2num($this->line->subprice * $this->multicurrency_tx);
  2323. $this->line->multicurrency_total_ht = $multicurrency_total_ht;
  2324. $this->line->multicurrency_total_tva = $multicurrency_total_tva;
  2325. $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
  2326. if (is_array($array_options) && count($array_options)>0) {
  2327. $this->line->array_options=$array_options;
  2328. }
  2329. $result=$this->line->update($user);
  2330. if ($result > 0)
  2331. {
  2332. // Reorder if child line
  2333. if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
  2334. // Mise a jour info denormalisees au niveau facture
  2335. $this->update_price(1);
  2336. $this->db->commit();
  2337. return $result;
  2338. }
  2339. else
  2340. {
  2341. $this->error=$this->line->error;
  2342. $this->db->rollback();
  2343. return -1;
  2344. }
  2345. }
  2346. else
  2347. {
  2348. $this->error="Invoice statut makes operation forbidden";
  2349. return -2;
  2350. }
  2351. }
  2352. /**
  2353. * Check if the percent edited is lower of next invoice line
  2354. *
  2355. * @param int $idline id of line to check
  2356. * @param float $situation_percent progress percentage need to be test
  2357. * @return false if KO, true if OK
  2358. */
  2359. function checkProgressLine($idline, $situation_percent)
  2360. {
  2361. $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
  2362. INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
  2363. WHERE fd.fk_prev_id = '.$idline.'
  2364. AND f.fk_statut <> 0';
  2365. $result = $this->db->query($sql);
  2366. if (! $result)
  2367. {
  2368. $this->error=$this->db->error();
  2369. return false;
  2370. }
  2371. $obj = $this->db->fetch_object($result);
  2372. if ($obj === null) return true;
  2373. else return $situation_percent < $obj->situation_percent;
  2374. }
  2375. /**
  2376. * Update invoice line with percentage
  2377. *
  2378. * @param FactureLigne $line Invoice line
  2379. * @param int $percent Percentage
  2380. * @return void
  2381. */
  2382. function update_percent($line, $percent)
  2383. {
  2384. global $mysoc,$user;
  2385. include_once(DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php');
  2386. // Cap percentages to 100
  2387. if ($percent > 100) $percent = 100;
  2388. $line->situation_percent = $percent;
  2389. $tabprice = calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->product_type, 'HT', 0, 0, $mysoc, '', $percent);
  2390. $line->total_ht = $tabprice[0];
  2391. $line->total_tva = $tabprice[1];
  2392. $line->total_ttc = $tabprice[2];
  2393. $line->total_localtax1 = $tabprice[9];
  2394. $line->total_localtax2 = $tabprice[10];
  2395. $line->update($user);
  2396. $this->update_price(1);
  2397. $this->db->commit();
  2398. }
  2399. /**
  2400. * Delete line in database
  2401. *
  2402. * @param int $rowid Id of line to delete
  2403. * @return int <0 if KO, >0 if OK
  2404. */
  2405. function deleteline($rowid)
  2406. {
  2407. dol_syslog(get_class($this)."::deleteline rowid=".$rowid, LOG_DEBUG);
  2408. if (! $this->brouillon)
  2409. {
  2410. $this->error='ErrorBadStatus';
  2411. return -1;
  2412. }
  2413. $this->db->begin();
  2414. // Libere remise liee a ligne de facture
  2415. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  2416. $sql.= ' SET fk_facture_line = NULL';
  2417. $sql.= ' WHERE fk_facture_line = '.$rowid;
  2418. dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
  2419. $result = $this->db->query($sql);
  2420. if (! $result)
  2421. {
  2422. $this->error=$this->db->error();
  2423. $this->db->rollback();
  2424. return -1;
  2425. }
  2426. $line=new FactureLigne($this->db);
  2427. $line->context = $this->context;
  2428. // For triggers
  2429. $line->fetch($rowid);
  2430. if ($line->delete() > 0)
  2431. {
  2432. $result=$this->update_price(1);
  2433. if ($result > 0)
  2434. {
  2435. $this->db->commit();
  2436. return 1;
  2437. }
  2438. else
  2439. {
  2440. $this->db->rollback();
  2441. $this->error=$this->db->lasterror();
  2442. return -1;
  2443. }
  2444. }
  2445. else
  2446. {
  2447. $this->db->rollback();
  2448. $this->error=$line->error;
  2449. return -1;
  2450. }
  2451. }
  2452. /**
  2453. * Set percent discount
  2454. *
  2455. * @param User $user User that set discount
  2456. * @param double $remise Discount
  2457. * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers
  2458. * @return int <0 if ko, >0 if ok
  2459. */
  2460. function set_remise($user, $remise, $notrigger=0)
  2461. {
  2462. // Clean parameters
  2463. if (empty($remise)) $remise=0;
  2464. if ($user->rights->facture->creer)
  2465. {
  2466. $remise=price2num($remise);
  2467. $error=0;
  2468. $this->db->begin();
  2469. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  2470. $sql.= ' SET remise_percent = '.$remise;
  2471. $sql.= ' WHERE rowid = '.$this->id;
  2472. $sql.= ' AND fk_statut = '.self::STATUS_DRAFT;
  2473. dol_syslog(__METHOD__, LOG_DEBUG);
  2474. $resql=$this->db->query($sql);
  2475. if (!$resql)
  2476. {
  2477. $this->errors[]=$this->db->error();
  2478. $error++;
  2479. }
  2480. if (! $notrigger && empty($error))
  2481. {
  2482. // Call trigger
  2483. $result=$this->call_trigger('BILL_MODIFY',$user);
  2484. if ($result < 0) $error++;
  2485. // End call triggers
  2486. }
  2487. if (! $error)
  2488. {
  2489. $this->remise_percent = $remise;
  2490. $this->update_price(1);
  2491. $this->db->commit();
  2492. return 1;
  2493. }
  2494. else
  2495. {
  2496. foreach($this->errors as $errmsg)
  2497. {
  2498. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2499. $this->error.=($this->error?', '.$errmsg:$errmsg);
  2500. }
  2501. $this->db->rollback();
  2502. return -1*$error;
  2503. }
  2504. }
  2505. }
  2506. /**
  2507. * Set absolute discount
  2508. *
  2509. * @param User $user User that set discount
  2510. * @param double $remise Discount
  2511. * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers
  2512. * @return int <0 if KO, >0 if OK
  2513. */
  2514. function set_remise_absolue($user, $remise, $notrigger=0)
  2515. {
  2516. if (empty($remise)) $remise=0;
  2517. if ($user->rights->facture->creer)
  2518. {
  2519. $error=0;
  2520. $this->db->begin();
  2521. $remise=price2num($remise);
  2522. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  2523. $sql.= ' SET remise_absolue = '.$remise;
  2524. $sql.= ' WHERE rowid = '.$this->id;
  2525. $sql.= ' AND fk_statut = '.self::STATUS_DRAFT;
  2526. dol_syslog(__METHOD__, LOG_DEBUG);
  2527. $resql=$this->db->query($sql);
  2528. if (!$resql)
  2529. {
  2530. $this->errors[]=$this->db->error();
  2531. $error++;
  2532. }
  2533. if (! $error)
  2534. {
  2535. $this->oldcopy= clone $this;
  2536. $this->remise_absolue = $remise;
  2537. $this->update_price(1);
  2538. }
  2539. if (! $notrigger && empty($error))
  2540. {
  2541. // Call trigger
  2542. $result=$this->call_trigger('BILL_MODIFY',$user);
  2543. if ($result < 0) $error++;
  2544. // End call triggers
  2545. }
  2546. if (! $error)
  2547. {
  2548. $this->db->commit();
  2549. return 1;
  2550. }
  2551. else
  2552. {
  2553. foreach($this->errors as $errmsg)
  2554. {
  2555. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2556. $this->error.=($this->error?', '.$errmsg:$errmsg);
  2557. }
  2558. $this->db->rollback();
  2559. return -1*$error;
  2560. }
  2561. }
  2562. }
  2563. /**
  2564. * Return list of payments
  2565. *
  2566. * @param string $filtertype 1 to filter on type of payment == 'PRE'
  2567. * @return array Array with list of payments
  2568. */
  2569. function getListOfPayments($filtertype='')
  2570. {
  2571. $retarray=array();
  2572. $table='paiement_facture';
  2573. $table2='paiement';
  2574. $field='fk_facture';
  2575. $field2='fk_paiement';
  2576. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
  2577. {
  2578. $table='paiementfourn_facturefourn';
  2579. $table2='paiementfourn';
  2580. $field='fk_facturefourn';
  2581. $field2='fk_paiementfourn';
  2582. }
  2583. $sql = 'SELECT pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, t.code';
  2584. $sql.= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t';
  2585. $sql.= ' WHERE pf.'.$field.' = '.$this->id;
  2586. $sql.= ' AND pf.'.$field2.' = p.rowid';
  2587. $sql.= ' AND p.fk_paiement = t.id';
  2588. if ($filtertype) $sql.=" AND t.code='PRE'";
  2589. dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG);
  2590. $resql=$this->db->query($sql);
  2591. if ($resql)
  2592. {
  2593. $num = $this->db->num_rows($resql);
  2594. $i=0;
  2595. while ($i < $num)
  2596. {
  2597. $obj = $this->db->fetch_object($resql);
  2598. $retarray[]=array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep);
  2599. $i++;
  2600. }
  2601. $this->db->free($resql);
  2602. return $retarray;
  2603. }
  2604. else
  2605. {
  2606. $this->error=$this->db->lasterror();
  2607. dol_print_error($this->db);
  2608. return array();
  2609. }
  2610. }
  2611. /**
  2612. * Return amount (with tax) of all credit notes and deposits invoices used by invoice
  2613. *
  2614. * @param int $multicurrency Return multicurrency_amount instead of amount
  2615. * @return int <0 if KO, Sum of credit notes and deposits amount otherwise
  2616. */
  2617. function getSumCreditNotesUsed($multicurrency=0)
  2618. {
  2619. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  2620. $discountstatic=new DiscountAbsolute($this->db);
  2621. $result=$discountstatic->getSumCreditNotesUsed($this, $multicurrency);
  2622. if ($result >= 0)
  2623. {
  2624. return $result;
  2625. }
  2626. else
  2627. {
  2628. $this->error=$discountstatic->error;
  2629. return -1;
  2630. }
  2631. }
  2632. /**
  2633. * Return amount (with tax) of all deposits invoices used by invoice
  2634. *
  2635. * @param int $multicurrency Return multicurrency_amount instead of amount
  2636. * @return int <0 if KO, Sum of deposits amount otherwise
  2637. */
  2638. function getSumDepositsUsed($multicurrency=0)
  2639. {
  2640. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  2641. $discountstatic=new DiscountAbsolute($this->db);
  2642. $result=$discountstatic->getSumDepositsUsed($this, $multicurrency);
  2643. if ($result >= 0)
  2644. {
  2645. return $result;
  2646. }
  2647. else
  2648. {
  2649. $this->error=$discountstatic->error;
  2650. return -1;
  2651. }
  2652. }
  2653. /**
  2654. * Return next reference of customer invoice not already used (or last reference)
  2655. * according to numbering module defined into constant FACTURE_ADDON
  2656. *
  2657. * @param Societe $soc object company
  2658. * @param string $mode 'next' for next value or 'last' for last value
  2659. * @return string free ref or last ref
  2660. */
  2661. function getNextNumRef($soc,$mode='next')
  2662. {
  2663. global $conf, $langs;
  2664. $langs->load("bills");
  2665. // Clean parameters (if not defined or using deprecated value)
  2666. if (empty($conf->global->FACTURE_ADDON)) $conf->global->FACTURE_ADDON='mod_facture_terre';
  2667. else if ($conf->global->FACTURE_ADDON=='terre') $conf->global->FACTURE_ADDON='mod_facture_terre';
  2668. else if ($conf->global->FACTURE_ADDON=='mercure') $conf->global->FACTURE_ADDON='mod_facture_mercure';
  2669. if (! empty($conf->global->FACTURE_ADDON))
  2670. {
  2671. $mybool=false;
  2672. $file = $conf->global->FACTURE_ADDON.".php";
  2673. $classname = $conf->global->FACTURE_ADDON;
  2674. // Include file with class
  2675. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2676. foreach ($dirmodels as $reldir) {
  2677. $dir = dol_buildpath($reldir."core/modules/facture/");
  2678. // Load file with numbering class (if found)
  2679. if (is_file($dir.$file) && is_readable($dir.$file))
  2680. {
  2681. $mybool |= include_once $dir . $file;
  2682. }
  2683. }
  2684. // For compatibility
  2685. if (! $mybool)
  2686. {
  2687. $file = $conf->global->FACTURE_ADDON."/".$conf->global->FACTURE_ADDON.".modules.php";
  2688. $classname = "mod_facture_".$conf->global->FACTURE_ADDON;
  2689. $classname = preg_replace('/\-.*$/','',$classname);
  2690. // Include file with class
  2691. foreach ($conf->file->dol_document_root as $dirroot)
  2692. {
  2693. $dir = $dirroot."/core/modules/facture/";
  2694. // Load file with numbering class (if found)
  2695. if (is_file($dir.$file) && is_readable($dir.$file)) {
  2696. $mybool |= include_once $dir . $file;
  2697. }
  2698. }
  2699. }
  2700. if (! $mybool)
  2701. {
  2702. dol_print_error('',"Failed to include file ".$file);
  2703. return '';
  2704. }
  2705. $obj = new $classname();
  2706. $numref = "";
  2707. $numref = $obj->getNextValue($soc,$this,$mode);
  2708. /**
  2709. * $numref can be empty in case we ask for the last value because if there is no invoice created with the
  2710. * set up mask.
  2711. */
  2712. if ($mode != 'last' && !$numref) {
  2713. dol_print_error($this->db,"Facture::getNextNumRef ".$obj->error);
  2714. return "";
  2715. }
  2716. return $numref;
  2717. }
  2718. else
  2719. {
  2720. $langs->load("errors");
  2721. print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete");
  2722. return "";
  2723. }
  2724. }
  2725. /**
  2726. * Load miscellaneous information for tab "Info"
  2727. *
  2728. * @param int $id Id of object to load
  2729. * @return void
  2730. */
  2731. function info($id)
  2732. {
  2733. $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
  2734. $sql.= ' fk_user_author, fk_user_valid';
  2735. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as c';
  2736. $sql.= ' WHERE c.rowid = '.$id;
  2737. $result=$this->db->query($sql);
  2738. if ($result)
  2739. {
  2740. if ($this->db->num_rows($result))
  2741. {
  2742. $obj = $this->db->fetch_object($result);
  2743. $this->id = $obj->rowid;
  2744. if ($obj->fk_user_author)
  2745. {
  2746. $cuser = new User($this->db);
  2747. $cuser->fetch($obj->fk_user_author);
  2748. $this->user_creation = $cuser;
  2749. }
  2750. if ($obj->fk_user_valid)
  2751. {
  2752. $vuser = new User($this->db);
  2753. $vuser->fetch($obj->fk_user_valid);
  2754. $this->user_validation = $vuser;
  2755. }
  2756. $this->date_creation = $this->db->jdate($obj->datec);
  2757. $this->date_modification = $this->db->jdate($obj->datem);
  2758. $this->date_validation = $this->db->jdate($obj->datev); // Should be in log table
  2759. }
  2760. $this->db->free($result);
  2761. }
  2762. else
  2763. {
  2764. dol_print_error($this->db);
  2765. }
  2766. }
  2767. /**
  2768. * Renvoi si les lignes de facture sont ventilees et/ou exportees en compta
  2769. *
  2770. * @return int <0 if KO, 0=no, 1=yes
  2771. */
  2772. function getVentilExportCompta()
  2773. {
  2774. // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
  2775. $ventilExportCompta = 0 ;
  2776. $num=count($this->lines);
  2777. for ($i = 0; $i < $num; $i++)
  2778. {
  2779. if (! empty($this->lines[$i]->export_compta) && ! empty($this->lines[$i]->code_ventilation))
  2780. {
  2781. $ventilExportCompta++;
  2782. }
  2783. }
  2784. if ($ventilExportCompta <> 0)
  2785. {
  2786. return 1;
  2787. }
  2788. else
  2789. {
  2790. return 0;
  2791. }
  2792. }
  2793. /**
  2794. * Return if an invoice can be deleted
  2795. * Rule is:
  2796. * If hidden option INVOICE_CAN_ALWAYS_BE_REMOVED is on, we can
  2797. * If invoice has a definitive ref, is last, without payment and not dipatched into accountancy -> yes end of rule
  2798. * If invoice is draft and ha a temporary ref -> yes
  2799. *
  2800. * @return int <0 if KO, 0=no, 1=yes
  2801. */
  2802. function is_erasable()
  2803. {
  2804. global $conf;
  2805. if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) return 1;
  2806. if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) return 0;
  2807. // on verifie si la facture est en numerotation provisoire
  2808. $facref = substr($this->ref, 1, 4);
  2809. // If not a draft invoice and not temporary invoice
  2810. if ($facref != 'PROV')
  2811. {
  2812. $maxfacnumber = $this->getNextNumRef($this->thirdparty,'last');
  2813. $ventilExportCompta = $this->getVentilExportCompta();
  2814. // If there is no invoice into the reset range and not already dispatched, we can delete
  2815. if ($maxfacnumber == '' && $ventilExportCompta == 0) return 1;
  2816. // If invoice to delete is last one and not already dispatched, we can delete
  2817. if ($maxfacnumber == $this->ref && $ventilExportCompta == 0) return 1;
  2818. if ($this->situation_cycle_ref) {
  2819. $last = $this->is_last_in_cycle();
  2820. return $last;
  2821. }
  2822. }
  2823. else if ($this->statut == self::STATUS_DRAFT && $facref == 'PROV') // Si facture brouillon et provisoire
  2824. {
  2825. return 1;
  2826. }
  2827. return 0;
  2828. }
  2829. /**
  2830. * Return list of invoices (eventually filtered on a user) into an array
  2831. *
  2832. * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
  2833. * @param int $draft 0=not draft, 1=draft
  2834. * @param User $excluser Objet user to exclude
  2835. * @param int $socid Id third pary
  2836. * @param int $limit For pagination
  2837. * @param int $offset For pagination
  2838. * @param string $sortfield Sort criteria
  2839. * @param string $sortorder Sort order
  2840. * @return int -1 if KO, array with result if OK
  2841. */
  2842. function liste_array($shortlist=0, $draft=0, $excluser='', $socid=0, $limit=0, $offset=0, $sortfield='f.datef,f.rowid', $sortorder='DESC')
  2843. {
  2844. global $conf,$user;
  2845. $ga = array();
  2846. $sql = "SELECT s.rowid, s.nom as name, s.client,";
  2847. $sql.= " f.rowid as fid, f.facnumber as ref, f.datef as df";
  2848. if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
  2849. $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
  2850. if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  2851. $sql.= " WHERE f.entity = ".$conf->entity;
  2852. $sql.= " AND f.fk_soc = s.rowid";
  2853. if (! $user->rights->societe->client->voir && ! $socid) //restriction
  2854. {
  2855. $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
  2856. }
  2857. if ($socid) $sql.= " AND s.rowid = ".$socid;
  2858. if ($draft) $sql.= " AND f.fk_statut = ".self::STATUS_DRAFT;
  2859. if (is_object($excluser)) $sql.= " AND f.fk_user_author <> ".$excluser->id;
  2860. $sql.= $this->db->order($sortfield,$sortorder);
  2861. $sql.= $this->db->plimit($limit,$offset);
  2862. $result=$this->db->query($sql);
  2863. if ($result)
  2864. {
  2865. $numc = $this->db->num_rows($result);
  2866. if ($numc)
  2867. {
  2868. $i = 0;
  2869. while ($i < $numc)
  2870. {
  2871. $obj = $this->db->fetch_object($result);
  2872. if ($shortlist == 1)
  2873. {
  2874. $ga[$obj->fid] = $obj->ref;
  2875. }
  2876. else if ($shortlist == 2)
  2877. {
  2878. $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
  2879. }
  2880. else
  2881. {
  2882. $ga[$i]['id'] = $obj->fid;
  2883. $ga[$i]['ref'] = $obj->ref;
  2884. $ga[$i]['name'] = $obj->name;
  2885. }
  2886. $i++;
  2887. }
  2888. }
  2889. return $ga;
  2890. }
  2891. else
  2892. {
  2893. dol_print_error($this->db);
  2894. return -1;
  2895. }
  2896. }
  2897. /**
  2898. * Renvoi liste des factures remplacables
  2899. * Statut validee ou abandonnee pour raison autre + non payee + aucun paiement + pas deja remplacee
  2900. *
  2901. * @param int $socid Id societe
  2902. * @return array Tableau des factures ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1)
  2903. */
  2904. function list_replacable_invoices($socid=0)
  2905. {
  2906. global $conf;
  2907. $return = array();
  2908. $sql = "SELECT f.rowid as rowid, f.facnumber, f.fk_statut,";
  2909. $sql.= " ff.rowid as rowidnext";
  2910. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
  2911. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
  2912. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
  2913. $sql.= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
  2914. $sql.= " AND f.entity = ".$conf->entity;
  2915. $sql.= " AND f.paye = 0"; // Pas classee payee completement
  2916. $sql.= " AND pf.fk_paiement IS NULL"; // Aucun paiement deja fait
  2917. $sql.= " AND ff.fk_statut IS NULL"; // Renvoi vrai si pas facture de remplacement
  2918. if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
  2919. $sql.= " ORDER BY f.facnumber";
  2920. dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
  2921. $resql=$this->db->query($sql);
  2922. if ($resql)
  2923. {
  2924. while ($obj=$this->db->fetch_object($resql))
  2925. {
  2926. $return[$obj->rowid]=array( 'id' => $obj->rowid,
  2927. 'ref' => $obj->facnumber,
  2928. 'status' => $obj->fk_statut);
  2929. }
  2930. //print_r($return);
  2931. return $return;
  2932. }
  2933. else
  2934. {
  2935. $this->error=$this->db->error();
  2936. return -1;
  2937. }
  2938. }
  2939. /**
  2940. * Renvoi liste des factures qualifiables pour correction par avoir
  2941. * Les factures qui respectent les regles suivantes sont retournees:
  2942. * (validee + paiement en cours) ou classee (payee completement ou payee partiellement) + pas deja remplacee + pas deja avoir
  2943. *
  2944. * @param int $socid Id societe
  2945. * @return array Tableau des factures ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>)
  2946. */
  2947. function list_qualified_avoir_invoices($socid=0)
  2948. {
  2949. global $conf;
  2950. $return = array();
  2951. $sql = "SELECT f.rowid as rowid, f.facnumber, f.fk_statut, f.type, f.paye, pf.fk_paiement";
  2952. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
  2953. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
  2954. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
  2955. $sql.= " WHERE f.entity = ".$conf->entity;
  2956. $sql.= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
  2957. // $sql.= " WHERE f.fk_statut >= 1";
  2958. // $sql.= " AND (f.paye = 1"; // Classee payee completement
  2959. // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
  2960. $sql.= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement
  2961. $sql.= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir
  2962. if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
  2963. $sql.= " ORDER BY f.facnumber";
  2964. dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
  2965. $resql=$this->db->query($sql);
  2966. if ($resql)
  2967. {
  2968. while ($obj=$this->db->fetch_object($resql))
  2969. {
  2970. $qualified=0;
  2971. if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified=1;
  2972. if ($obj->fk_statut == self::STATUS_CLOSED) $qualified=1;
  2973. if ($qualified)
  2974. {
  2975. //$ref=$obj->facnumber;
  2976. $paymentornot=($obj->fk_paiement?1:0);
  2977. $return[$obj->rowid]=array('ref'=>$obj->facnumber,'status'=>$obj->fk_statut,'type'=>$obj->type,'paye'=>$obj->paye,'paymentornot'=>$paymentornot);
  2978. }
  2979. }
  2980. return $return;
  2981. }
  2982. else
  2983. {
  2984. $this->error=$this->db->error();
  2985. return -1;
  2986. }
  2987. }
  2988. /**
  2989. * Create a withdrawal request for a standing order
  2990. *
  2991. * @param User $fuser User asking standing order
  2992. * @param float $amount Amount we request withdraw for
  2993. * @return int <0 if KO, >0 if OK
  2994. */
  2995. function demande_prelevement($fuser, $amount=0)
  2996. {
  2997. $error=0;
  2998. dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
  2999. if ($this->statut > self::STATUS_DRAFT && $this->paye == 0)
  3000. {
  3001. require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
  3002. $bac = new CompanyBankAccount($this->db);
  3003. $bac->fetch(0,$this->socid);
  3004. $sql = 'SELECT count(*)';
  3005. $sql.= ' FROM '.MAIN_DB_PREFIX.'prelevement_facture_demande';
  3006. $sql.= ' WHERE fk_facture = '.$this->id;
  3007. $sql.= ' AND traite = 0';
  3008. dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
  3009. $resql=$this->db->query($sql);
  3010. if ($resql)
  3011. {
  3012. $row = $this->db->fetch_row($resql);
  3013. if ($row[0] == 0)
  3014. {
  3015. $now=dol_now();
  3016. $totalpaye = $this->getSommePaiement();
  3017. $totalcreditnotes = $this->getSumCreditNotesUsed();
  3018. $totaldeposits = $this->getSumDepositsUsed();
  3019. //print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
  3020. // We can also use bcadd to avoid pb with floating points
  3021. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  3022. //$resteapayer=bcadd($this->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
  3023. //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  3024. if (empty($amount)) $amount = price2num($this->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT');
  3025. if (is_numeric($amount) && $amount != 0)
  3026. {
  3027. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'prelevement_facture_demande';
  3028. $sql .= ' (fk_facture, amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib)';
  3029. $sql .= ' VALUES ('.$this->id;
  3030. $sql .= ",'".price2num($amount)."'";
  3031. $sql .= ",'".$this->db->idate($now)."'";
  3032. $sql .= ",".$fuser->id;
  3033. $sql .= ",'".$bac->code_banque."'";
  3034. $sql .= ",'".$bac->code_guichet."'";
  3035. $sql .= ",'".$bac->number."'";
  3036. $sql .= ",'".$bac->cle_rib."')";
  3037. dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
  3038. $resql=$this->db->query($sql);
  3039. if (! $resql)
  3040. {
  3041. $this->error=$this->db->lasterror();
  3042. dol_syslog(get_class($this).'::demandeprelevement Erreur');
  3043. $error++;
  3044. }
  3045. }
  3046. else
  3047. {
  3048. $this->error='WithdrawRequestErrorNilAmount';
  3049. dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount');
  3050. $error++;
  3051. }
  3052. if (! $error)
  3053. {
  3054. // Force payment mode of invoice to withdraw
  3055. $payment_mode_id = dol_getIdFromCode($this->db, 'PRE', 'c_paiement');
  3056. if ($payment_mode_id > 0)
  3057. {
  3058. $result=$this->setPaymentMethods($payment_mode_id);
  3059. }
  3060. }
  3061. if ($error) return -1;
  3062. return 1;
  3063. }
  3064. else
  3065. {
  3066. $this->error="A request already exists";
  3067. dol_syslog(get_class($this).'::demandeprelevement Impossible de creer une demande, demande deja en cours');
  3068. return 0;
  3069. }
  3070. }
  3071. else
  3072. {
  3073. $this->error=$this->db->error();
  3074. dol_syslog(get_class($this).'::demandeprelevement Erreur -2');
  3075. return -2;
  3076. }
  3077. }
  3078. else
  3079. {
  3080. $this->error="Status of invoice does not allow this";
  3081. dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id");
  3082. return -3;
  3083. }
  3084. }
  3085. /**
  3086. * Supprime une demande de prelevement
  3087. *
  3088. * @param User $fuser User making delete
  3089. * @param int $did id de la demande a supprimer
  3090. * @return int <0 if OK, >0 if KO
  3091. */
  3092. function demande_prelevement_delete($fuser, $did)
  3093. {
  3094. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'prelevement_facture_demande';
  3095. $sql .= ' WHERE rowid = '.$did;
  3096. $sql .= ' AND traite = 0';
  3097. if ( $this->db->query($sql) )
  3098. {
  3099. return 0;
  3100. }
  3101. else
  3102. {
  3103. $this->error=$this->db->lasterror();
  3104. dol_syslog(get_class($this).'::demande_prelevement_delete Error '.$this->error);
  3105. return -1;
  3106. }
  3107. }
  3108. /**
  3109. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  3110. *
  3111. * @param User $user Object user
  3112. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  3113. */
  3114. function load_board($user)
  3115. {
  3116. global $conf, $langs;
  3117. $clause = " WHERE";
  3118. $sql = "SELECT f.rowid, f.date_lim_reglement as datefin,f.fk_statut";
  3119. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
  3120. if (!$user->rights->societe->client->voir && !$user->societe_id)
  3121. {
  3122. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
  3123. $sql.= " WHERE sc.fk_user = " .$user->id;
  3124. $clause = " AND";
  3125. }
  3126. $sql.= $clause." f.paye=0";
  3127. $sql.= " AND f.entity = ".$conf->entity;
  3128. $sql.= " AND f.fk_statut = ".self::STATUS_VALIDATED;
  3129. if ($user->societe_id) $sql.= " AND f.fk_soc = ".$user->societe_id;
  3130. $resql=$this->db->query($sql);
  3131. if ($resql)
  3132. {
  3133. $langs->load("bills");
  3134. $now=dol_now();
  3135. $response = new WorkboardResponse();
  3136. $response->warning_delay=$conf->facture->client->warning_delay/60/60/24;
  3137. $response->label=$langs->trans("CustomerBillsUnpaid");
  3138. $response->url=DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=accountancy&leftmenu=customers_bills';
  3139. $response->img=img_object($langs->trans("Bills"),"bill");
  3140. $generic_facture = new Facture($this->db);
  3141. while ($obj=$this->db->fetch_object($resql))
  3142. {
  3143. $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
  3144. $generic_facture->statut = $obj->fk_statut;
  3145. $response->nbtodo++;
  3146. if ($generic_facture->hasDelay()) {
  3147. $response->nbtodolate++;
  3148. }
  3149. }
  3150. return $response;
  3151. }
  3152. else
  3153. {
  3154. dol_print_error($this->db);
  3155. $this->error=$this->db->error();
  3156. return -1;
  3157. }
  3158. }
  3159. /* gestion des contacts d'une facture */
  3160. /**
  3161. * Retourne id des contacts clients de facturation
  3162. *
  3163. * @return array Liste des id contacts facturation
  3164. */
  3165. function getIdBillingContact()
  3166. {
  3167. return $this->getIdContact('external','BILLING');
  3168. }
  3169. /**
  3170. * Retourne id des contacts clients de livraison
  3171. *
  3172. * @return array Liste des id contacts livraison
  3173. */
  3174. function getIdShippingContact()
  3175. {
  3176. return $this->getIdContact('external','SHIPPING');
  3177. }
  3178. /**
  3179. * Initialise an instance with random values.
  3180. * Used to build previews or test instances.
  3181. * id must be 0 if object instance is a specimen.
  3182. *
  3183. * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines
  3184. * @return void
  3185. */
  3186. function initAsSpecimen($option='')
  3187. {
  3188. global $langs;
  3189. $now=dol_now();
  3190. $arraynow=dol_getdate($now);
  3191. $nownotime=dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
  3192. // Load array of products prodids
  3193. $num_prods = 0;
  3194. $prodids = array();
  3195. $sql = "SELECT rowid";
  3196. $sql.= " FROM ".MAIN_DB_PREFIX."product";
  3197. $sql.= " WHERE entity IN (".getEntity('product', 1).")";
  3198. $resql = $this->db->query($sql);
  3199. if ($resql)
  3200. {
  3201. $num_prods = $this->db->num_rows($resql);
  3202. $i = 0;
  3203. while ($i < $num_prods)
  3204. {
  3205. $i++;
  3206. $row = $this->db->fetch_row($resql);
  3207. $prodids[$i] = $row[0];
  3208. }
  3209. }
  3210. //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
  3211. if (empty($num_prods)) {
  3212. $num_prods=1;
  3213. }
  3214. // Initialize parameters
  3215. $this->id=0;
  3216. $this->ref = 'SPECIMEN';
  3217. $this->specimen=1;
  3218. $this->socid = 1;
  3219. $this->date = $nownotime;
  3220. $this->date_lim_reglement = $nownotime + 3600 * 24 *30;
  3221. $this->cond_reglement_id = 1;
  3222. $this->cond_reglement_code = 'RECEP';
  3223. $this->date_lim_reglement=$this->calculate_date_lim_reglement();
  3224. $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
  3225. $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
  3226. $this->note_public='This is a comment (public)';
  3227. $this->note_private='This is a comment (private)';
  3228. $this->note='This is a comment (private)';
  3229. $this->fk_incoterms=0;
  3230. $this->location_incoterms='';
  3231. if (empty($option) || $option != 'nolines')
  3232. {
  3233. // Lines
  3234. $nbp = 5;
  3235. $xnbp = 0;
  3236. while ($xnbp < $nbp)
  3237. {
  3238. $line=new FactureLigne($this->db);
  3239. $line->desc=$langs->trans("Description")." ".$xnbp;
  3240. $line->qty=1;
  3241. $line->subprice=100;
  3242. $line->tva_tx=19.6;
  3243. $line->localtax1_tx=0;
  3244. $line->localtax2_tx=0;
  3245. $line->remise_percent=0;
  3246. if ($xnbp == 1) // Qty is negative (product line)
  3247. {
  3248. $prodid = mt_rand(1, $num_prods);
  3249. $line->fk_product=$prodids[$prodid];
  3250. $line->qty=-1;
  3251. $line->total_ht=-100;
  3252. $line->total_ttc=-119.6;
  3253. $line->total_tva=-19.6;
  3254. }
  3255. else if ($xnbp == 2) // UP is negative (free line)
  3256. {
  3257. $line->subprice=-100;
  3258. $line->total_ht=-100;
  3259. $line->total_ttc=-119.6;
  3260. $line->total_tva=-19.6;
  3261. $line->remise_percent=0;
  3262. }
  3263. else if ($xnbp == 3) // Discount is 50% (product line)
  3264. {
  3265. $prodid = mt_rand(1, $num_prods);
  3266. $line->fk_product=$prodids[$prodid];
  3267. $line->total_ht=50;
  3268. $line->total_ttc=59.8;
  3269. $line->total_tva=9.8;
  3270. $line->remise_percent=50;
  3271. }
  3272. else // (product line)
  3273. {
  3274. $prodid = mt_rand(1, $num_prods);
  3275. $line->fk_product=$prodids[$prodid];
  3276. $line->total_ht=100;
  3277. $line->total_ttc=119.6;
  3278. $line->total_tva=19.6;
  3279. $line->remise_percent=00;
  3280. }
  3281. $this->lines[$xnbp]=$line;
  3282. $xnbp++;
  3283. $this->total_ht += $line->total_ht;
  3284. $this->total_tva += $line->total_tva;
  3285. $this->total_ttc += $line->total_ttc;
  3286. }
  3287. $this->revenuestamp = 0;
  3288. // Add a line "offered"
  3289. $line=new FactureLigne($this->db);
  3290. $line->desc=$langs->trans("Description")." (offered line)";
  3291. $line->qty=1;
  3292. $line->subprice=100;
  3293. $line->tva_tx=19.6;
  3294. $line->localtax1_tx=0;
  3295. $line->localtax2_tx=0;
  3296. $line->remise_percent=100;
  3297. $line->total_ht=0;
  3298. $line->total_ttc=0; // 90 * 1.196
  3299. $line->total_tva=0;
  3300. $prodid = mt_rand(1, $num_prods);
  3301. $line->fk_product=$prodids[$prodid];
  3302. $this->lines[$xnbp]=$line;
  3303. $xnbp++;
  3304. }
  3305. }
  3306. /**
  3307. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  3308. *
  3309. * @return int <0 if KO, >0 if OK
  3310. */
  3311. function load_state_board()
  3312. {
  3313. global $conf, $user;
  3314. $this->nb=array();
  3315. $clause = "WHERE";
  3316. $sql = "SELECT count(f.rowid) as nb";
  3317. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
  3318. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
  3319. if (!$user->rights->societe->client->voir && !$user->societe_id)
  3320. {
  3321. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  3322. $sql.= " WHERE sc.fk_user = " .$user->id;
  3323. $clause = "AND";
  3324. }
  3325. $sql.= " ".$clause." f.entity = ".$conf->entity;
  3326. $resql=$this->db->query($sql);
  3327. if ($resql)
  3328. {
  3329. while ($obj=$this->db->fetch_object($resql))
  3330. {
  3331. $this->nb["invoices"]=$obj->nb;
  3332. }
  3333. $this->db->free($resql);
  3334. return 1;
  3335. }
  3336. else
  3337. {
  3338. dol_print_error($this->db);
  3339. $this->error=$this->db->error();
  3340. return -1;
  3341. }
  3342. }
  3343. /**
  3344. * Create an array of invoice lines
  3345. *
  3346. * @return int >0 if OK, <0 if KO
  3347. */
  3348. function getLinesArray()
  3349. {
  3350. return $this->fetch_lines();
  3351. }
  3352. /**
  3353. * Create a document onto disk according to template module.
  3354. *
  3355. * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
  3356. * @param Translate $outputlangs objet lang a utiliser pour traduction
  3357. * @param int $hidedetails Hide details of lines
  3358. * @param int $hidedesc Hide description
  3359. * @param int $hideref Hide ref
  3360. * @return int <0 if KO, >0 if OK
  3361. */
  3362. public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
  3363. {
  3364. global $conf,$langs;
  3365. $langs->load("bills");
  3366. // Positionne le modele sur le nom du modele a utiliser
  3367. if (! dol_strlen($modele))
  3368. {
  3369. if (! empty($conf->global->FACTURE_ADDON_PDF))
  3370. {
  3371. $modele = $conf->global->FACTURE_ADDON_PDF;
  3372. }
  3373. else
  3374. {
  3375. $modele = 'crabe';
  3376. }
  3377. }
  3378. $modelpath = "core/modules/facture/doc/";
  3379. $result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  3380. return $result;
  3381. }
  3382. /**
  3383. * Gets the smallest reference available for a new cycle
  3384. *
  3385. * @return int >= 1 if OK, -1 if error
  3386. */
  3387. function newCycle()
  3388. {
  3389. $sql = 'SELECT max(situation_cycle_ref) FROM ' . MAIN_DB_PREFIX . 'facture as f';
  3390. $sql.= " WHERE f.entity in (".getEntity('facture').")";
  3391. $resql = $this->db->query($sql);
  3392. if ($resql) {
  3393. if ($resql->num_rows > 0)
  3394. {
  3395. $res = $this->db->fetch_array($resql);
  3396. $ref = $res['max(situation_cycle_ref)'];
  3397. $ref++;
  3398. } else {
  3399. $ref = 1;
  3400. }
  3401. $this->db->free($resql);
  3402. return $ref;
  3403. } else {
  3404. $this->error = $this->db->lasterror();
  3405. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  3406. return -1;
  3407. }
  3408. }
  3409. /**
  3410. * Checks if the invoice is the first of a cycle
  3411. *
  3412. * @return boolean
  3413. */
  3414. function is_first()
  3415. {
  3416. return ($this->situation_counter == 1);
  3417. }
  3418. /**
  3419. * Returns an array containing the previous situations as Facture objects
  3420. *
  3421. * @return mixed -1 if error, array of previous situations
  3422. */
  3423. function get_prev_sits()
  3424. {
  3425. global $conf;
  3426. $sql = 'SELECT rowid FROM ' . MAIN_DB_PREFIX . 'facture';
  3427. $sql .= ' where situation_cycle_ref = ' . $this->situation_cycle_ref;
  3428. $sql .= ' and situation_counter < ' . $this->situation_counter;
  3429. $sql .= ' AND entity = '. ($this->entity > 0 ? $this->entity : $conf->entity);
  3430. $resql = $this->db->query($sql);
  3431. $res = array();
  3432. if ($resql && $resql->num_rows > 0) {
  3433. while ($row = $this->db->fetch_object($resql)) {
  3434. $id = $row->rowid;
  3435. $situation = new Facture($this->db);
  3436. $situation->fetch($id);
  3437. $res[] = $situation;
  3438. }
  3439. } else {
  3440. $this->error = $this->db->error();
  3441. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  3442. return -1;
  3443. }
  3444. return $res;
  3445. }
  3446. /**
  3447. * Sets the invoice as a final situation
  3448. *
  3449. * @param User $user Object user
  3450. * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers
  3451. * @return int <0 if KO, >0 if OK
  3452. */
  3453. function setFinal(User $user, $notrigger=0)
  3454. {
  3455. $error=0;
  3456. $this->db->begin();
  3457. $this->situation_final = 1;
  3458. $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'facture SET situation_final = ' . $this->situation_final . ' where rowid = ' . $this->id;
  3459. dol_syslog(__METHOD__, LOG_DEBUG);
  3460. $resql=$this->db->query($sql);
  3461. if (!$resql)
  3462. {
  3463. $this->errors[]=$this->db->error();
  3464. $error++;
  3465. }
  3466. if (! $notrigger && empty($error))
  3467. {
  3468. // Call trigger
  3469. $result=$this->call_trigger('BILL_MODIFY',$user);
  3470. if ($result < 0) $error++;
  3471. // End call triggers
  3472. }
  3473. if (! $error)
  3474. {
  3475. $this->db->commit();
  3476. return 1;
  3477. }
  3478. else
  3479. {
  3480. foreach($this->errors as $errmsg)
  3481. {
  3482. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  3483. $this->error.=($this->error?', '.$errmsg:$errmsg);
  3484. }
  3485. $this->db->rollback();
  3486. return -1*$error;
  3487. }
  3488. }
  3489. /**
  3490. * Checks if the invoice is the last in its cycle
  3491. *
  3492. * @return bool Last of the cycle status
  3493. *
  3494. */
  3495. function is_last_in_cycle()
  3496. {
  3497. global $conf;
  3498. if (!empty($this->situation_cycle_ref)) {
  3499. // No point in testing anything if we're not inside a cycle
  3500. $sql = 'SELECT max(situation_counter) FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_cycle_ref = ' . $this->situation_cycle_ref . ' AND entity = ' . ($this->entity > 0 ? $this->entity : $conf->entity);
  3501. $resql = $this->db->query($sql);
  3502. if ($resql && $resql->num_rows > 0) {
  3503. $res = $this->db->fetch_array($resql);
  3504. $last = $res['max(situation_counter)'];
  3505. return ($last == $this->situation_counter);
  3506. } else {
  3507. $this->error = $this->db->lasterror();
  3508. dol_syslog(get_class($this) . "::select Error " . $this->error, LOG_ERR);
  3509. return false;
  3510. }
  3511. } else {
  3512. return true;
  3513. }
  3514. }
  3515. /**
  3516. * Function used to replace a thirdparty id with another one.
  3517. *
  3518. * @param DoliDB $db Database handler
  3519. * @param int $origin_id Old thirdparty id
  3520. * @param int $dest_id New thirdparty id
  3521. * @return bool
  3522. */
  3523. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  3524. {
  3525. $tables = array(
  3526. 'facture'
  3527. );
  3528. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  3529. }
  3530. /**
  3531. * Is the customer invoice delayed?
  3532. *
  3533. * @return bool
  3534. */
  3535. public function hasDelay()
  3536. {
  3537. global $conf;
  3538. $now = dol_now();
  3539. // Paid invoices have status STATUS_CLOSED
  3540. if ($this->statut != Facture::STATUS_VALIDATED) return false;
  3541. return $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
  3542. }
  3543. }
  3544. /**
  3545. * Class to manage invoice lines.
  3546. * Saved into database table llx_facturedet
  3547. */
  3548. class FactureLigne extends CommonInvoiceLine
  3549. {
  3550. public $element='facturedet';
  3551. public $table_element='facturedet';
  3552. var $oldline;
  3553. //! From llx_facturedet
  3554. //! Id facture
  3555. var $fk_facture;
  3556. //! Id parent line
  3557. var $fk_parent_line;
  3558. /**
  3559. * @deprecated
  3560. */
  3561. var $label;
  3562. //! Description ligne
  3563. var $desc;
  3564. var $localtax1_type; // Local tax 1 type
  3565. var $localtax2_type; // Local tax 2 type
  3566. var $fk_remise_except; // Link to line into llx_remise_except
  3567. var $rang = 0;
  3568. var $fk_fournprice;
  3569. var $pa_ht;
  3570. var $marge_tx;
  3571. var $marque_tx;
  3572. var $special_code; // Liste d'options non cumulabels:
  3573. // 1: frais de port
  3574. // 2: ecotaxe
  3575. // 3: ??
  3576. var $origin;
  3577. var $origin_id;
  3578. var $fk_code_ventilation = 0;
  3579. var $date_start;
  3580. var $date_end;
  3581. // Ne plus utiliser
  3582. //var $price; // P.U. HT apres remise % de ligne (exemple 80)
  3583. //var $remise; // Montant calcule de la remise % sur PU HT (exemple 20)
  3584. // From llx_product
  3585. /**
  3586. * @deprecated
  3587. * @see product_ref
  3588. */
  3589. var $ref; // Product ref (deprecated)
  3590. var $product_ref; // Product ref
  3591. /**
  3592. * @deprecated
  3593. * @see product_label
  3594. */
  3595. var $libelle; // Product label (deprecated)
  3596. var $product_label; // Product label
  3597. var $product_desc; // Description produit
  3598. var $skip_update_total; // Skip update price total for special lines
  3599. /**
  3600. * @var int Situation advance percentage
  3601. */
  3602. public $situation_percent;
  3603. /**
  3604. * @var int Previous situation line id reference
  3605. */
  3606. public $fk_prev_id;
  3607. // Multicurrency
  3608. var $fk_multicurrency;
  3609. var $multicurrency_code;
  3610. var $multicurrency_subprice;
  3611. var $multicurrency_total_ht;
  3612. var $multicurrency_total_tva;
  3613. var $multicurrency_total_ttc;
  3614. /**
  3615. * Load invoice line from database
  3616. *
  3617. * @param int $rowid id of invoice line to get
  3618. * @return int <0 if KO, >0 if OK
  3619. */
  3620. function fetch($rowid)
  3621. {
  3622. $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.tva_tx,';
  3623. $sql.= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice,';
  3624. $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,';
  3625. $sql.= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
  3626. $sql.= ' fd.fk_code_ventilation,';
  3627. $sql.= ' fd.fk_unit,';
  3628. $sql.= ' fd.situation_percent, fd.fk_prev_id,';
  3629. $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc';
  3630. $sql.= ' , fd.multicurrency_subprice';
  3631. $sql.= ' , fd.multicurrency_total_ht';
  3632. $sql.= ' , fd.multicurrency_total_tva';
  3633. $sql.= ' , fd.multicurrency_total_ttc';
  3634. $sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
  3635. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
  3636. $sql.= ' WHERE fd.rowid = '.$rowid;
  3637. $result = $this->db->query($sql);
  3638. if ($result)
  3639. {
  3640. $objp = $this->db->fetch_object($result);
  3641. $this->rowid = $objp->rowid;
  3642. $this->fk_facture = $objp->fk_facture;
  3643. $this->fk_parent_line = $objp->fk_parent_line;
  3644. $this->label = $objp->custom_label;
  3645. $this->desc = $objp->description;
  3646. $this->qty = $objp->qty;
  3647. $this->subprice = $objp->subprice;
  3648. $this->tva_tx = $objp->tva_tx;
  3649. $this->localtax1_tx = $objp->localtax1_tx;
  3650. $this->localtax2_tx = $objp->localtax2_tx;
  3651. $this->remise_percent = $objp->remise_percent;
  3652. $this->fk_remise_except = $objp->fk_remise_except;
  3653. $this->fk_product = $objp->fk_product;
  3654. $this->product_type = $objp->product_type;
  3655. $this->date_start = $this->db->jdate($objp->date_start);
  3656. $this->date_end = $this->db->jdate($objp->date_end);
  3657. $this->info_bits = $objp->info_bits;
  3658. $this->special_code = $objp->special_code;
  3659. $this->total_ht = $objp->total_ht;
  3660. $this->total_tva = $objp->total_tva;
  3661. $this->total_localtax1 = $objp->total_localtax1;
  3662. $this->total_localtax2 = $objp->total_localtax2;
  3663. $this->total_ttc = $objp->total_ttc;
  3664. $this->fk_code_ventilation = $objp->fk_code_ventilation;
  3665. $this->rang = $objp->rang;
  3666. $this->fk_fournprice = $objp->fk_fournprice;
  3667. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
  3668. $this->pa_ht = $marginInfos[0];
  3669. $this->marge_tx = $marginInfos[1];
  3670. $this->marque_tx = $marginInfos[2];
  3671. $this->ref = $objp->product_ref; // deprecated
  3672. $this->product_ref = $objp->product_ref;
  3673. $this->libelle = $objp->product_libelle; // deprecated
  3674. $this->product_label = $objp->product_libelle;
  3675. $this->product_desc = $objp->product_desc;
  3676. $this->fk_unit = $objp->fk_unit;
  3677. $this->situation_percent = $objp->situation_percent;
  3678. $this->fk_prev_id = $objp->fk_prev_id;
  3679. $this->multicurrency_subprice = $objp->multicurrency_subprice;
  3680. $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
  3681. $this->multicurrency_total_tva= $objp->multicurrency_total_tva;
  3682. $this->multicurrency_total_ttc= $objp->multicurrency_total_ttc;
  3683. $this->db->free($result);
  3684. return 1;
  3685. }
  3686. else
  3687. {
  3688. return -1;
  3689. }
  3690. }
  3691. /**
  3692. * Insert line into database
  3693. *
  3694. * @param int $notrigger 1 no triggers
  3695. * @return int <0 if KO, >0 if OK
  3696. */
  3697. function insert($notrigger=0)
  3698. {
  3699. global $langs,$user,$conf;
  3700. $error=0;
  3701. $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'.
  3702. dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
  3703. // Clean parameters
  3704. $this->desc=trim($this->desc);
  3705. if (empty($this->tva_tx)) $this->tva_tx=0;
  3706. if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
  3707. if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
  3708. if (empty($this->localtax1_type)) $this->localtax1_type=0;
  3709. if (empty($this->localtax2_type)) $this->localtax2_type=0;
  3710. if (empty($this->total_localtax1)) $this->total_localtax1=0;
  3711. if (empty($this->total_localtax2)) $this->total_localtax2=0;
  3712. if (empty($this->rang)) $this->rang=0;
  3713. if (empty($this->remise_percent)) $this->remise_percent=0;
  3714. if (empty($this->info_bits)) $this->info_bits=0;
  3715. if (empty($this->subprice)) $this->subprice=0;
  3716. if (empty($this->special_code)) $this->special_code=0;
  3717. if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
  3718. if (empty($this->fk_prev_id)) $this->fk_prev_id = 'null';
  3719. if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
  3720. if (empty($this->pa_ht)) $this->pa_ht=0;
  3721. if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
  3722. if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
  3723. if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
  3724. if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
  3725. // if buy price not defined, define buyprice as configured in margin admin
  3726. if ($this->pa_ht == 0 && $pa_ht_isemptystring)
  3727. {
  3728. if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
  3729. {
  3730. return $result;
  3731. }
  3732. else
  3733. {
  3734. $this->pa_ht = $result;
  3735. }
  3736. }
  3737. // Check parameters
  3738. if ($this->product_type < 0)
  3739. {
  3740. $this->error='ErrorProductTypeMustBe0orMore';
  3741. return -1;
  3742. }
  3743. if (! empty($this->fk_product))
  3744. {
  3745. // Check product exists
  3746. $result=Product::isExistingObject('product', $this->fk_product);
  3747. if ($result <= 0)
  3748. {
  3749. $this->error='ErrorProductIdDoesNotExists';
  3750. return -1;
  3751. }
  3752. }
  3753. $this->db->begin();
  3754. // Insertion dans base de la ligne
  3755. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet';
  3756. $sql.= ' (fk_facture, fk_parent_line, label, description, qty,';
  3757. $sql.= ' tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
  3758. $sql.= ' fk_product, product_type, remise_percent, subprice, fk_remise_except,';
  3759. $sql.= ' date_start, date_end, fk_code_ventilation, ';
  3760. $sql.= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
  3761. $sql.= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
  3762. $sql.= ' situation_percent, fk_prev_id,';
  3763. $sql.= ' fk_unit';
  3764. $sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3765. $sql.= ')';
  3766. $sql.= " VALUES (".$this->fk_facture.",";
  3767. $sql.= " ".($this->fk_parent_line>0?"'".$this->fk_parent_line."'":"null").",";
  3768. $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
  3769. $sql.= " '".$this->db->escape($this->desc)."',";
  3770. $sql.= " ".price2num($this->qty).",";
  3771. $sql.= " ".price2num($this->tva_tx).",";
  3772. $sql.= " ".price2num($this->localtax1_tx).",";
  3773. $sql.= " ".price2num($this->localtax2_tx).",";
  3774. $sql.= " '".$this->localtax1_type."',";
  3775. $sql.= " '".$this->localtax2_type."',";
  3776. $sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").',';
  3777. $sql.= " ".$this->product_type.",";
  3778. $sql.= " ".price2num($this->remise_percent).",";
  3779. $sql.= " ".price2num($this->subprice).",";
  3780. $sql.= ' '.(! empty($this->fk_remise_except)?$this->fk_remise_except:"null").',';
  3781. $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").",";
  3782. $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").",";
  3783. $sql.= ' '.$this->fk_code_ventilation.',';
  3784. $sql.= ' '.$this->rang.',';
  3785. $sql.= ' '.$this->special_code.',';
  3786. $sql.= ' '.(! empty($this->fk_fournprice)?$this->fk_fournprice:"null").',';
  3787. $sql.= ' '.price2num($this->pa_ht).',';
  3788. $sql.= " '".$this->info_bits."',";
  3789. $sql.= " ".price2num($this->total_ht).",";
  3790. $sql.= " ".price2num($this->total_tva).",";
  3791. $sql.= " ".price2num($this->total_ttc).",";
  3792. $sql.= " ".price2num($this->total_localtax1).",";
  3793. $sql.= " ".price2num($this->total_localtax2);
  3794. $sql .= ", " . $this->situation_percent;
  3795. $sql .= ", " . $this->fk_prev_id;
  3796. $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
  3797. $sql.= ", ".(int) $this->fk_multicurrency;
  3798. $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
  3799. $sql.= ", ".price2num($this->multicurrency_subprice);
  3800. $sql.= ", ".price2num($this->multicurrency_total_ht);
  3801. $sql.= ", ".price2num($this->multicurrency_total_tva);
  3802. $sql.= ", ".price2num($this->multicurrency_total_ttc);
  3803. $sql.= ')';
  3804. dol_syslog(get_class($this)."::insert", LOG_DEBUG);
  3805. $resql=$this->db->query($sql);
  3806. if ($resql)
  3807. {
  3808. $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
  3809. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  3810. {
  3811. $this->id=$this->rowid;
  3812. $result=$this->insertExtraFields();
  3813. if ($result < 0)
  3814. {
  3815. $error++;
  3816. }
  3817. }
  3818. // Si fk_remise_except defini, on lie la remise a la facture
  3819. // ce qui la flague comme "consommee".
  3820. if ($this->fk_remise_except)
  3821. {
  3822. $discount=new DiscountAbsolute($this->db);
  3823. $result=$discount->fetch($this->fk_remise_except);
  3824. if ($result >= 0)
  3825. {
  3826. // Check if discount was found
  3827. if ($result > 0)
  3828. {
  3829. // Check if discount not already affected to another invoice
  3830. if ($discount->fk_facture)
  3831. {
  3832. $this->error=$langs->trans("ErrorDiscountAlreadyUsed",$discount->id);
  3833. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  3834. $this->db->rollback();
  3835. return -3;
  3836. }
  3837. else
  3838. {
  3839. $result=$discount->link_to_invoice($this->rowid,0);
  3840. if ($result < 0)
  3841. {
  3842. $this->error=$discount->error;
  3843. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  3844. $this->db->rollback();
  3845. return -3;
  3846. }
  3847. }
  3848. }
  3849. else
  3850. {
  3851. $this->error=$langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
  3852. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  3853. $this->db->rollback();
  3854. return -3;
  3855. }
  3856. }
  3857. else
  3858. {
  3859. $this->error=$discount->error;
  3860. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  3861. $this->db->rollback();
  3862. return -3;
  3863. }
  3864. }
  3865. if (! $notrigger)
  3866. {
  3867. // Call trigger
  3868. $result=$this->call_trigger('LINEBILL_INSERT',$user);
  3869. if ($result < 0)
  3870. {
  3871. $this->db->rollback();
  3872. return -2;
  3873. }
  3874. // End call triggers
  3875. }
  3876. $this->db->commit();
  3877. return $this->rowid;
  3878. }
  3879. else
  3880. {
  3881. $this->error=$this->db->error();
  3882. $this->db->rollback();
  3883. return -2;
  3884. }
  3885. }
  3886. /**
  3887. * Update line into database
  3888. *
  3889. * @param User $user User object
  3890. * @param int $notrigger Disable triggers
  3891. * @return int <0 if KO, >0 if OK
  3892. */
  3893. function update($user='',$notrigger=0)
  3894. {
  3895. global $user,$conf;
  3896. $error=0;
  3897. $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'.
  3898. // Clean parameters
  3899. $this->desc=trim($this->desc);
  3900. if (empty($this->tva_tx)) $this->tva_tx=0;
  3901. if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
  3902. if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
  3903. if (empty($this->localtax1_type)) $this->localtax1_type=0;
  3904. if (empty($this->localtax2_type)) $this->localtax2_type=0;
  3905. if (empty($this->total_localtax1)) $this->total_localtax1=0;
  3906. if (empty($this->total_localtax2)) $this->total_localtax2=0;
  3907. if (empty($this->remise_percent)) $this->remise_percent=0;
  3908. if (empty($this->info_bits)) $this->info_bits=0;
  3909. if (empty($this->special_code)) $this->special_code=0;
  3910. if (empty($this->product_type)) $this->product_type=0;
  3911. if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
  3912. if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
  3913. if (empty($this->pa_ht)) $this->pa_ht=0;
  3914. if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
  3915. if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
  3916. if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
  3917. if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
  3918. // Check parameters
  3919. if ($this->product_type < 0) return -1;
  3920. // if buy price not defined, define buyprice as configured in margin admin
  3921. if ($this->pa_ht == 0 && $pa_ht_isemptystring)
  3922. {
  3923. if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
  3924. {
  3925. return $result;
  3926. }
  3927. else
  3928. {
  3929. $this->pa_ht = $result;
  3930. }
  3931. }
  3932. $this->db->begin();
  3933. // Mise a jour ligne en base
  3934. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
  3935. $sql.= " description='".$this->db->escape($this->desc)."'";
  3936. $sql.= ",label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
  3937. $sql.= ",subprice=".price2num($this->subprice)."";
  3938. $sql.= ",remise_percent=".price2num($this->remise_percent)."";
  3939. if ($this->fk_remise_except) $sql.= ",fk_remise_except=".$this->fk_remise_except;
  3940. else $sql.= ",fk_remise_except=null";
  3941. $sql.= ",tva_tx=".price2num($this->tva_tx)."";
  3942. $sql.= ",localtax1_tx=".price2num($this->localtax1_tx)."";
  3943. $sql.= ",localtax2_tx=".price2num($this->localtax2_tx)."";
  3944. $sql.= ",localtax1_type='".$this->localtax1_type."'";
  3945. $sql.= ",localtax2_type='".$this->localtax2_type."'";
  3946. $sql.= ",qty=".price2num($this->qty)."";
  3947. $sql.= ",date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
  3948. $sql.= ",date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
  3949. $sql.= ",product_type=".$this->product_type;
  3950. $sql.= ",info_bits='".$this->info_bits."'";
  3951. $sql.= ",special_code='".$this->special_code."'";
  3952. if (empty($this->skip_update_total))
  3953. {
  3954. $sql.= ",total_ht=".price2num($this->total_ht)."";
  3955. $sql.= ",total_tva=".price2num($this->total_tva)."";
  3956. $sql.= ",total_ttc=".price2num($this->total_ttc)."";
  3957. $sql.= ",total_localtax1=".price2num($this->total_localtax1)."";
  3958. $sql.= ",total_localtax2=".price2num($this->total_localtax2)."";
  3959. }
  3960. $sql.= " , fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null");
  3961. $sql.= " , buy_price_ht='".price2num($this->pa_ht)."'";
  3962. $sql.= ",fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null");
  3963. if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
  3964. $sql .= ", situation_percent=" . $this->situation_percent;
  3965. $sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
  3966. // Multicurrency
  3967. $sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
  3968. $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
  3969. $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
  3970. $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
  3971. $sql.= " WHERE rowid = ".$this->rowid;
  3972. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  3973. $resql=$this->db->query($sql);
  3974. if ($resql)
  3975. {
  3976. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  3977. {
  3978. $this->id=$this->rowid;
  3979. $result=$this->insertExtraFields();
  3980. if ($result < 0)
  3981. {
  3982. $error++;
  3983. }
  3984. }
  3985. if (! $notrigger)
  3986. {
  3987. // Call trigger
  3988. $result=$this->call_trigger('LINEBILL_UPDATE',$user);
  3989. if ($result < 0)
  3990. {
  3991. $this->db->rollback();
  3992. return -2;
  3993. }
  3994. // End call triggers
  3995. }
  3996. $this->db->commit();
  3997. return 1;
  3998. }
  3999. else
  4000. {
  4001. $this->error=$this->db->error();
  4002. $this->db->rollback();
  4003. return -2;
  4004. }
  4005. }
  4006. /**
  4007. * Delete line in database
  4008. *
  4009. * @return int <0 if KO, >0 if OK
  4010. */
  4011. function delete()
  4012. {
  4013. global $user;
  4014. $this->db->begin();
  4015. // Call trigger
  4016. $result=$this->call_trigger('LINEBILL_DELETE',$user);
  4017. if ($result < 0)
  4018. {
  4019. $this->db->rollback();
  4020. return -1;
  4021. }
  4022. // End call triggers
  4023. $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".$this->rowid;
  4024. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  4025. if ($this->db->query($sql) )
  4026. {
  4027. $this->db->commit();
  4028. return 1;
  4029. }
  4030. else
  4031. {
  4032. $this->error=$this->db->error()." sql=".$sql;
  4033. $this->db->rollback();
  4034. return -1;
  4035. }
  4036. }
  4037. /**
  4038. * Mise a jour en base des champs total_xxx de ligne de facture
  4039. *
  4040. * @return int <0 if KO, >0 if OK
  4041. */
  4042. function update_total()
  4043. {
  4044. $this->db->begin();
  4045. dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
  4046. // Clean parameters
  4047. if (empty($this->total_localtax1)) $this->total_localtax1=0;
  4048. if (empty($this->total_localtax2)) $this->total_localtax2=0;
  4049. // Mise a jour ligne en base
  4050. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
  4051. $sql.= " total_ht=".price2num($this->total_ht)."";
  4052. $sql.= ",total_tva=".price2num($this->total_tva)."";
  4053. $sql.= ",total_localtax1=".price2num($this->total_localtax1)."";
  4054. $sql.= ",total_localtax2=".price2num($this->total_localtax2)."";
  4055. $sql.= ",total_ttc=".price2num($this->total_ttc)."";
  4056. $sql.= " WHERE rowid = ".$this->rowid;
  4057. dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
  4058. $resql=$this->db->query($sql);
  4059. if ($resql)
  4060. {
  4061. $this->db->commit();
  4062. return 1;
  4063. }
  4064. else
  4065. {
  4066. $this->error=$this->db->error();
  4067. $this->db->rollback();
  4068. return -2;
  4069. }
  4070. }
  4071. /**
  4072. * Returns situation_percent of the previous line.
  4073. * Warning: If invoice is a replacement invoice, this->fk_prev_id is id of the replaced line.
  4074. *
  4075. * @param int $invoiceid Invoice id
  4076. * @return int >= 0
  4077. */
  4078. function get_prev_progress($invoiceid)
  4079. {
  4080. if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
  4081. return 0;
  4082. } else {
  4083. // If invoice is a not a situation invoice, this->fk_prev_id is used for something else
  4084. $tmpinvoice=new Facture($this->db);
  4085. $tmpinvoice->fetch($invoiceid);
  4086. if ($tmpinvoice->type != Facture::TYPE_SITUATION) return 0;
  4087. $sql = 'SELECT situation_percent FROM ' . MAIN_DB_PREFIX . 'facturedet WHERE rowid=' . $this->fk_prev_id;
  4088. $resql = $this->db->query($sql);
  4089. if ($resql && $resql->num_rows > 0) {
  4090. $res = $this->db->fetch_array($resql);
  4091. return $res['situation_percent'];
  4092. } else {
  4093. $this->error = $this->db->error();
  4094. dol_syslog(get_class($this) . "::select Error " . $this->error, LOG_ERR);
  4095. $this->db->rollback();
  4096. return -1;
  4097. }
  4098. }
  4099. }
  4100. }