facture.class.php 147 KB

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