fournisseur.facture.class.php 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118
  1. <?php
  2. /* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  5. * Copyright (C) 2005 Marc Barilley <marc@ocebo.com>
  6. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
  7. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  8. * Copyright (C) 2013-2019 Philippe Grand <philippe.grand@atoo-net.com>
  9. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  10. * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2015 Bahfir Abbes <bafbes@gmail.com>
  12. * Copyright (C) 2015-2022 Ferran Marcet <fmarcet@2byte.es>
  13. * Copyright (C) 2016-2023 Alexandre Spangaro <aspangaro@open-dsi.fr>
  14. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  15. * Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  17. *
  18. * This program is free software; you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation; either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  30. */
  31. /**
  32. * \file htdocs/fourn/class/fournisseur.facture.class.php
  33. * \ingroup fournisseur,facture
  34. * \brief File of class to manage suppliers invoices
  35. */
  36. include_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  40. if (isModEnabled('accounting')) {
  41. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
  43. }
  44. /**
  45. * Class to manage suppliers invoices
  46. */
  47. class FactureFournisseur extends CommonInvoice
  48. {
  49. /**
  50. * @var string ID to identify managed object
  51. */
  52. public $element = 'invoice_supplier';
  53. /**
  54. * @var string Name of table without prefix where object is stored
  55. */
  56. public $table_element = 'facture_fourn';
  57. /**
  58. * @var string Name of subtable line
  59. */
  60. public $table_element_line = 'facture_fourn_det';
  61. /**
  62. * @var string Field with ID of parent key if this field has a parent
  63. */
  64. public $fk_element = 'fk_facture_fourn';
  65. /**
  66. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  67. */
  68. public $picto = 'supplier_invoice';
  69. /**
  70. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  71. * @var int
  72. */
  73. public $ismultientitymanaged = 1;
  74. /**
  75. * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  76. * @var integer
  77. */
  78. public $restrictiononfksoc = 1;
  79. /**
  80. * {@inheritdoc}
  81. */
  82. protected $table_ref_field = 'ref';
  83. /**
  84. * @var int ID
  85. */
  86. public $rowid;
  87. /**
  88. * @var string Ref
  89. */
  90. public $ref;
  91. /**
  92. * @var string Ref supplier
  93. */
  94. public $ref_supplier;
  95. /**
  96. * @var string Label of invoice
  97. */
  98. public $label;
  99. public $socid;
  100. //Check constants for types
  101. public $type = self::TYPE_STANDARD;
  102. /**
  103. * Supplier invoice status
  104. * @var int
  105. * @see FactureFournisseur::STATUS_DRAFT, FactureFournisseur::STATUS_VALIDATED, FactureFournisseur::STATUS_PAID, FactureFournisseur::STATUS_ABANDONED
  106. */
  107. public $statut;
  108. /**
  109. * Supplier invoice status
  110. * @var int
  111. * @see FactureFournisseur::STATUS_DRAFT, FactureFournisseur::STATUS_VALIDATED, FactureFournisseur::STATUS_PAID, FactureFournisseur::STATUS_ABANDONED
  112. */
  113. public $status;
  114. /**
  115. * ! Closing after partial payment: discount_vat, badsupplier, abandon
  116. * ! Closing when no payment: replaced, abandoned
  117. * @var string Close code
  118. */
  119. public $close_code;
  120. /**
  121. * ! Comment if paid without full payment
  122. * @var string Close note
  123. */
  124. public $close_note;
  125. /**
  126. * Set to 1 if the invoice is completely paid, otherwise is 0
  127. * @var int
  128. */
  129. public $paye;
  130. public $author;
  131. /**
  132. * Date creation record (datec)
  133. *
  134. * @var integer
  135. */
  136. public $datec;
  137. /**
  138. * Date modification record (tms)
  139. *
  140. * @var integer
  141. */
  142. public $tms;
  143. /**
  144. * Invoice date (date)
  145. *
  146. * @var integer
  147. */
  148. public $date;
  149. /**
  150. * Max payment date (date_echeance)
  151. *
  152. * @var integer
  153. */
  154. public $date_echeance;
  155. /**
  156. * @var double $amount
  157. * @deprecated
  158. */
  159. public $amount = 0;
  160. /**
  161. * @var double $remise
  162. * @deprecated
  163. */
  164. public $remise = 0;
  165. /**
  166. * @var float tva
  167. * @deprecated Use $total_tva
  168. */
  169. public $tva;
  170. // Warning: Do not set default value into property defintion. it must stay null.
  171. // For example to avoid to have substition done when object is generic and not yet defined.
  172. public $localtax1;
  173. public $localtax2;
  174. public $total_ht;
  175. public $total_tva;
  176. public $total_localtax1;
  177. public $total_localtax2;
  178. public $total_ttc;
  179. /**
  180. * @deprecated
  181. * @see $note_private, $note_public
  182. */
  183. public $note;
  184. public $note_private;
  185. public $note_public;
  186. public $propalid;
  187. public $cond_reglement_id;
  188. public $cond_reglement_code;
  189. public $cond_reglement_label;
  190. public $cond_reglement_doc;
  191. /**
  192. * @var int ID
  193. */
  194. public $fk_account; // default bank account
  195. public $mode_reglement_id;
  196. public $mode_reglement_code;
  197. /**
  198. * @var int transport mode id
  199. */
  200. public $transport_mode_id;
  201. /**
  202. * @var boolean VAT reverse charge can be used on the invoice
  203. */
  204. public $vat_reverse_charge;
  205. public $extraparams = array();
  206. /**
  207. * Invoice lines
  208. * @var SupplierInvoiceLine[]
  209. */
  210. public $lines = array();
  211. /**
  212. * @deprecated
  213. */
  214. public $fournisseur;
  215. // Multicurrency
  216. /**
  217. * @var int ID
  218. */
  219. public $fk_multicurrency;
  220. public $multicurrency_code;
  221. public $multicurrency_tx;
  222. public $multicurrency_total_ht;
  223. public $multicurrency_total_tva;
  224. public $multicurrency_total_ttc;
  225. //! id of source invoice if replacement invoice or credit note
  226. /**
  227. * @var int ID
  228. */
  229. public $fk_facture_source;
  230. public $fac_rec;
  231. public $fields = array(
  232. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  233. 'ref' =>array('type'=>'varchar(255)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>15),
  234. 'ref_supplier' =>array('type'=>'varchar(255)', 'label'=>'RefSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
  235. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>25, 'index'=>1),
  236. 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>30),
  237. 'type' =>array('type'=>'smallint(6)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
  238. 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'isModEnabled("societe")', 'visible'=>-1, 'notnull'=>1, 'position'=>40),
  239. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
  240. 'datef' =>array('type'=>'date', 'label'=>'Date', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
  241. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>55),
  242. 'libelle' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
  243. 'paye' =>array('type'=>'smallint(6)', 'label'=>'Paye', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>65),
  244. 'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
  245. 'remise' =>array('type'=>'double(24,8)', 'label'=>'Discount', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
  246. 'close_code' =>array('type'=>'varchar(16)', 'label'=>'CloseCode', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
  247. 'close_note' =>array('type'=>'varchar(128)', 'label'=>'CloseNote', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
  248. 'tva' =>array('type'=>'double(24,8)', 'label'=>'Tva', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  249. 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
  250. 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
  251. 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
  252. 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'TotalVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
  253. 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
  254. 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
  255. 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>130),
  256. 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
  257. 'fk_facture_source' =>array('type'=>'integer', 'label'=>'Fk facture source', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
  258. 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>"isModEnabled('project')", 'visible'=>-1, 'position'=>145),
  259. 'fk_account' =>array('type'=>'integer', 'label'=>'Account', 'enabled'=>'isModEnabled("banque")', 'visible'=>-1, 'position'=>150),
  260. 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>155),
  261. 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
  262. 'date_lim_reglement' =>array('type'=>'date', 'label'=>'DateLimReglement', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
  263. 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>170),
  264. 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>175),
  265. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'ModelPdf', 'enabled'=>1, 'visible'=>0, 'position'=>180),
  266. 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
  267. 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
  268. 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLocation', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
  269. 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyId', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
  270. 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
  271. 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
  272. 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>220),
  273. 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>225),
  274. 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>230),
  275. 'date_pointoftax' =>array('type'=>'date', 'label'=>'Date pointoftax', 'enabled'=>1, 'visible'=>-1, 'position'=>235),
  276. 'date_valid' =>array('type'=>'date', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>240),
  277. 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'Last main doc', 'enabled'=>1, 'visible'=>-1, 'position'=>245),
  278. 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
  279. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900),
  280. );
  281. /**
  282. * Standard invoice
  283. */
  284. const TYPE_STANDARD = 0;
  285. /**
  286. * Replacement invoice
  287. */
  288. const TYPE_REPLACEMENT = 1;
  289. /**
  290. * Credit note invoice
  291. */
  292. const TYPE_CREDIT_NOTE = 2;
  293. /**
  294. * Deposit invoice
  295. */
  296. const TYPE_DEPOSIT = 3;
  297. /**
  298. * Draft
  299. */
  300. const STATUS_DRAFT = 0;
  301. /**
  302. * Validated (need to be paid)
  303. */
  304. const STATUS_VALIDATED = 1;
  305. /**
  306. * Classified paid.
  307. * If paid partially, $this->close_code can be:
  308. * - CLOSECODE_DISCOUNTVAT
  309. * - CLOSECODE_BADCREDIT
  310. * If paid completelly, this->close_code will be null
  311. */
  312. const STATUS_CLOSED = 2;
  313. /**
  314. * Classified abandoned and no payment done.
  315. * $this->close_code can be:
  316. * - CLOSECODE_BADCREDIT
  317. * - CLOSECODE_ABANDONED
  318. * - CLOSECODE_REPLACED
  319. */
  320. const STATUS_ABANDONED = 3;
  321. const CLOSECODE_DISCOUNTVAT = 'discount_vat';
  322. const CLOSECODE_BADCREDIT = 'badsupplier';
  323. const CLOSECODE_ABANDONED = 'abandon';
  324. const CLOSECODE_REPLACED = 'replaced';
  325. /**
  326. * Constructor
  327. *
  328. * @param DoliDB $db Database handler
  329. */
  330. public function __construct($db)
  331. {
  332. $this->db = $db;
  333. }
  334. /**
  335. * Create supplier invoice into database
  336. *
  337. * @param User $user user object that creates
  338. * @return int Id invoice created if OK, < 0 if KO
  339. */
  340. public function create($user)
  341. {
  342. global $langs, $conf, $hookmanager;
  343. $error = 0;
  344. $now = dol_now();
  345. // Clean parameters
  346. if (isset($this->ref_supplier)) {
  347. $this->ref_supplier = trim($this->ref_supplier);
  348. }
  349. if (empty($this->type)) {
  350. $this->type = self::TYPE_STANDARD;
  351. }
  352. if (empty($this->date)) {
  353. $this->date = $now;
  354. }
  355. // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
  356. if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
  357. list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
  358. } else {
  359. $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  360. }
  361. if (empty($this->fk_multicurrency)) {
  362. $this->multicurrency_code = $conf->currency;
  363. $this->fk_multicurrency = 0;
  364. $this->multicurrency_tx = 1;
  365. }
  366. $this->db->begin();
  367. // Create invoice from a template recurring invoice
  368. if ($this->fac_rec > 0) {
  369. $this->fk_fac_rec_source = $this->fac_rec;
  370. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture-rec.class.php';
  371. $_facrec = new FactureFournisseurRec($this->db);
  372. $result = $_facrec->fetch($this->fac_rec);
  373. $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
  374. // Define some dates
  375. if (!empty($_facrec->frequency)) {
  376. $originaldatewhen = $_facrec->date_when;
  377. $nextdatewhen = dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
  378. $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd');
  379. $this->socid = $_facrec->socid;
  380. }
  381. $this->entity = $_facrec->entity; // Invoice created in same entity than template
  382. // 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
  383. $this->fk_project = GETPOST('projectid', 'int') > 0 ? ((int) GETPOST('projectid', 'int')) : $_facrec->fk_projet;
  384. $this->fk_projet = $this->fk_project;
  385. $this->note_public = GETPOST('note_public', 'restricthtml') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
  386. $this->note_private = GETPOST('note_private', 'restricthtml') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
  387. $this->model_pdf = GETPOST('model', 'alpha') ? GETPOST('model', 'alpha') : $_facrec->model_pdf;
  388. $this->cond_reglement_id = GETPOST('cond_reglement_id', 'int') > 0 ? ((int) GETPOST('cond_reglement_id', 'int')) : $_facrec->cond_reglement_id;
  389. $this->mode_reglement_id = GETPOST('mode_reglement_id', 'int') > 0 ? ((int) GETPOST('mode_reglement_id', 'int')) : $_facrec->mode_reglement_id;
  390. $this->fk_account = GETPOST('fk_account') > 0 ? ((int) GETPOST('fk_account')) : $_facrec->fk_account;
  391. // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
  392. $this->total_ht = $_facrec->total_ht;
  393. $this->total_ttc = $_facrec->total_ttc;
  394. // Fields always coming from template
  395. $this->fk_incoterms = $_facrec->fk_incoterms;
  396. $this->location_incoterms = $_facrec->location_incoterms;
  397. // Clean parameters
  398. if (! $this->type) {
  399. $this->type = self::TYPE_STANDARD;
  400. }
  401. if (!empty(GETPOST('ref_supplier'))) {
  402. $this->ref_supplier = trim($this->ref_supplier);
  403. } else {
  404. $this->ref_supplier = trim($this->ref_supplier . '_' . ($_facrec->nb_gen_done + 1));
  405. }
  406. $this->note_public = trim($this->note_public);
  407. $this->note_private = trim($this->note_private);
  408. $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->titre));
  409. $this->array_options = $_facrec->array_options;
  410. if (! $this->mode_reglement_id) {
  411. $this->mode_reglement_id = 0;
  412. }
  413. $this->brouillon = 1;
  414. $this->status = self::STATUS_DRAFT;
  415. $this->statut = self::STATUS_DRAFT;
  416. $this->linked_objects = $_facrec->linkedObjectsIds;
  417. // We do not add link to template invoice or next invoice will be linked to all generated invoices
  418. //$this->linked_objects['facturerec'][0] = $this->fac_rec;
  419. $forceduedate = $this->calculate_date_lim_reglement();
  420. // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
  421. if ($_facrec->frequency > 0) {
  422. dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
  423. if (empty($_facrec->date_when)) {
  424. $_facrec->date_when = $now;
  425. }
  426. $next_date = $_facrec->getNextDate(); // Calculate next date
  427. $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
  428. //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
  429. $result = $_facrec->setNextDate($next_date, 1);
  430. }
  431. // Define lang of customer
  432. $outputlangs = $langs;
  433. $newlang = '';
  434. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
  435. $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
  436. }
  437. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
  438. $newlang = $this->default_lang; // for thirdparty
  439. }
  440. if (!empty($newlang)) {
  441. $outputlangs = new Translate("", $conf);
  442. $outputlangs->setDefaultLang($newlang);
  443. }
  444. // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
  445. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
  446. $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m');
  447. $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
  448. $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m');
  449. $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B');
  450. $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
  451. $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B');
  452. $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y');
  453. $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
  454. $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y');
  455. // Only for template invoice
  456. $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = dol_print_date($originaldatewhen, 'dayhour');
  457. $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($nextdatewhen, 'dayhour');
  458. $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($previousdaynextdatewhen, 'dayhour');
  459. $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
  460. $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
  461. complete_substitutions_array($substitutionarray, $outputlangs);
  462. $this->note_public = make_substitutions($this->note_public, $substitutionarray);
  463. $this->note_private = make_substitutions($this->note_private, $substitutionarray);
  464. }
  465. // Define due date if not already defined
  466. if (!empty($forceduedate)) {
  467. $this->date_echeance = $forceduedate;
  468. }
  469. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn (";
  470. $sql .= "ref";
  471. $sql .= ", ref_supplier";
  472. $sql .= ", ref_ext";
  473. $sql .= ", entity";
  474. $sql .= ", type";
  475. $sql .= ", libelle";
  476. $sql .= ", fk_soc";
  477. $sql .= ", datec";
  478. $sql .= ", datef";
  479. $sql .= ", vat_reverse_charge";
  480. $sql .= ", fk_projet";
  481. $sql .= ", fk_cond_reglement";
  482. $sql .= ", fk_mode_reglement";
  483. $sql .= ", fk_account";
  484. $sql .= ", note_private";
  485. $sql .= ", note_public";
  486. $sql .= ", fk_user_author";
  487. $sql .= ", date_lim_reglement";
  488. $sql .= ", fk_incoterms, location_incoterms";
  489. $sql .= ", fk_multicurrency";
  490. $sql .= ", multicurrency_code";
  491. $sql .= ", multicurrency_tx";
  492. $sql .= ", fk_facture_source";
  493. $sql .= ", fk_fac_rec_source";
  494. $sql .= ")";
  495. $sql .= " VALUES (";
  496. $sql .= "'(PROV)'";
  497. $sql .= ", '".$this->db->escape($this->ref_supplier)."'";
  498. $sql .= ", '".$this->db->escape($this->ref_ext)."'";
  499. $sql .= ", ".((int) $conf->entity);
  500. $sql .= ", '".$this->db->escape($this->type)."'";
  501. $sql .= ", '".$this->db->escape(isset($this->label) ? $this->label : (isset($this->libelle) ? $this->libelle : ''))."'";
  502. $sql .= ", ".((int) $this->socid);
  503. $sql .= ", '".$this->db->idate($now)."'";
  504. $sql .= ", '".$this->db->idate($this->date)."'";
  505. $sql .= ", ".($this->vat_reverse_charge != '' ? ((int) $this->db->escape($this->vat_reverse_charge)) : 0);
  506. $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
  507. $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
  508. $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
  509. $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
  510. $sql .= ", '".$this->db->escape($this->note_private)."'";
  511. $sql .= ", '".$this->db->escape($this->note_public)."'";
  512. $sql .= ", ".((int) $user->id).",";
  513. $sql .= $this->date_echeance != '' ? "'".$this->db->idate($this->date_echeance)."'" : "null";
  514. $sql .= ", ".(int) $this->fk_incoterms;
  515. $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
  516. $sql .= ", ".(int) $this->fk_multicurrency;
  517. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  518. $sql .= ", ".(double) $this->multicurrency_tx;
  519. $sql .= ", ".($this->fk_facture_source ? ((int) $this->fk_facture_source) : "null");
  520. $sql .= ", ".(isset($this->fk_fac_rec_source) ? $this->fk_fac_rec_source : "NULL");
  521. $sql .= ")";
  522. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  523. $resql = $this->db->query($sql);
  524. if ($resql) {
  525. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn');
  526. // Update ref with new one
  527. $this->ref = '(PROV'.$this->id.')';
  528. $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
  529. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  530. $resql = $this->db->query($sql);
  531. if (!$resql) {
  532. $error++;
  533. }
  534. if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
  535. $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
  536. }
  537. // Add object linked
  538. if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
  539. foreach ($this->linked_objects as $origin => $tmp_origin_id) {
  540. if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
  541. foreach ($tmp_origin_id as $origin_id) {
  542. $ret = $this->add_object_linked($origin, $origin_id);
  543. if (!$ret) {
  544. dol_print_error($this->db);
  545. $error++;
  546. }
  547. }
  548. } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
  549. {
  550. $origin_id = $tmp_origin_id;
  551. $ret = $this->add_object_linked($origin, $origin_id);
  552. if (!$ret) {
  553. dol_print_error($this->db);
  554. $error++;
  555. }
  556. }
  557. }
  558. }
  559. if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode)
  560. dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
  561. foreach ($this->lines as $i => $val) {
  562. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code, fk_remise_except)';
  563. $sql .= " VALUES (".((int) $this->id).", ".((int) $this->lines[$i]->special_code).", ".($this->lines[$i]->fk_remise_except > 0 ? ((int) $this->lines[$i]->fk_remise_except) : 'NULL').')';
  564. $resql_insert = $this->db->query($sql);
  565. if ($resql_insert) {
  566. $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
  567. $res = $this->updateline(
  568. $idligne,
  569. $this->lines[$i]->description,
  570. $this->lines[$i]->subprice,
  571. $this->lines[$i]->tva_tx.($this->lines[$i]->vat_src_code ? ' ('.$this->lines[$i]->vat_src_code.')' : ''),
  572. $this->lines[$i]->localtax1_tx,
  573. $this->lines[$i]->localtax2_tx,
  574. $this->lines[$i]->qty,
  575. $this->lines[$i]->fk_product,
  576. 'HT',
  577. (!empty($this->lines[$i]->info_bits) ? $this->lines[$i]->info_bits : ''),
  578. $this->lines[$i]->product_type,
  579. $this->lines[$i]->remise_percent,
  580. false,
  581. $this->lines[$i]->date_start,
  582. $this->lines[$i]->date_end,
  583. $this->lines[$i]->array_options,
  584. $this->lines[$i]->fk_unit,
  585. $this->lines[$i]->multicurrency_subprice,
  586. $this->lines[$i]->ref_supplier
  587. );
  588. } else {
  589. $this->error = $this->db->lasterror();
  590. $this->db->rollback();
  591. return -5;
  592. }
  593. }
  594. } elseif (!$error && empty($this->fac_rec)) { // If this->lines is an array of invoice line arrays
  595. dol_syslog("There is ".count($this->lines)." lines that are array lines");
  596. foreach ($this->lines as $i => $val) {
  597. $line = $this->lines[$i];
  598. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  599. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  600. if (!is_object($line)) {
  601. $line = (object) $line;
  602. }
  603. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code, fk_remise_except)';
  604. $sql .= " VALUES (".((int) $this->id).", ".((int) $this->lines[$i]->special_code).", ".($this->lines[$i]->fk_remise_except > 0 ? ((int) $this->lines[$i]->fk_remise_except) : 'NULL').')';
  605. $resql_insert = $this->db->query($sql);
  606. if ($resql_insert) {
  607. $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
  608. $this->updateline(
  609. $idligne,
  610. $line->description,
  611. $line->pu_ht,
  612. $line->tva_tx,
  613. $line->localtax1_tx,
  614. $line->localtax2_tx,
  615. $line->qty,
  616. $line->fk_product,
  617. 'HT',
  618. (!empty($line->info_bits) ? $line->info_bits : ''),
  619. $line->product_type,
  620. $line->remise_percent,
  621. 0,
  622. $line->date_start,
  623. $line->date_end,
  624. $line->array_options,
  625. $line->fk_unit,
  626. $line->multicurrency_subprice,
  627. $line->ref_supplier
  628. );
  629. } else {
  630. $this->error = $this->db->lasterror();
  631. $this->db->rollback();
  632. return -5;
  633. }
  634. }
  635. }
  636. /*
  637. * Insert lines of template invoices
  638. */
  639. if (! $error && $this->fac_rec > 0) {
  640. foreach ($_facrec->lines as $i => $val) {
  641. if ($_facrec->lines[$i]->fk_product) {
  642. $prod = new Product($this->db);
  643. $res = $prod->fetch($_facrec->lines[$i]->fk_product);
  644. }
  645. // For line from template invoice, we use data from template invoice
  646. /*
  647. $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
  648. $tva_npr = get_default_npr($mysoc,$soc,$prod->id);
  649. if (empty($tva_tx)) $tva_npr=0;
  650. $localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
  651. $localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
  652. */
  653. $tva_tx = $_facrec->lines[$i]->tva_tx . ($_facrec->lines[$i]->vat_src_code ? '(' . $_facrec->lines[$i]->vat_src_code . ')' : '');
  654. $tva_npr = $_facrec->lines[$i]->info_bits;
  655. if (empty($tva_tx)) {
  656. $tva_npr = 0;
  657. }
  658. $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
  659. $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
  660. $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
  661. $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
  662. // If buyprice not defined from template invoice, we try to guess the best value
  663. if (! $buyprice && $_facrec->lines[$i]->fk_product > 0) {
  664. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
  665. $producttmp = new ProductFournisseur($this->db);
  666. $producttmp->fetch($_facrec->lines[$i]->fk_product);
  667. // If margin module defined on costprice, we try the costprice
  668. // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
  669. // else we get the best supplier price
  670. if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) {
  671. $buyprice = $producttmp->cost_price;
  672. } elseif (isModEnabled('stock') && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) {
  673. $buyprice = $producttmp->pmp;
  674. } else {
  675. if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
  676. if ($producttmp->product_fourn_price_id > 0) {
  677. $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
  678. }
  679. }
  680. }
  681. }
  682. $result_insert = $this->addline(
  683. $_facrec->lines[$i]->description,
  684. $_facrec->lines[$i]->pu_ht,
  685. $tva_tx,
  686. $localtax1_tx,
  687. $localtax2_tx,
  688. $_facrec->lines[$i]->qty,
  689. $_facrec->lines[$i]->fk_product,
  690. $_facrec->lines[$i]->remise_percent,
  691. ($_facrec->lines[$i]->date_start == 1 && $this->date) ? $this->date : '',
  692. ($_facrec->lines[$i]->date_end == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
  693. 0,
  694. $_facrec->lines[$i]->info_bits,
  695. 'HT',
  696. 0,
  697. $_facrec->lines[$i]->rang,
  698. false,
  699. $_facrec->lines[$i]->array_options,
  700. $_facrec->lines[$i]->fk_unit,
  701. 0,
  702. 0,
  703. $_facrec->lines[$i]->ref_supplier,
  704. $_facrec->lines[$i]->special_code,
  705. 0,
  706. 0
  707. );
  708. if ($result_insert < 0) {
  709. $error++;
  710. $this->error = $this->db->error();
  711. break;
  712. }
  713. }
  714. }
  715. // Update total price
  716. $result = $this->update_price(1);
  717. if ($result > 0) {
  718. // Actions on extra fields
  719. if (!$error) {
  720. $result = $this->insertExtraFields(); // This also set $this->error or $this->errors if errors are found
  721. if ($result < 0) {
  722. $error++;
  723. }
  724. }
  725. if (!$error) {
  726. // Call trigger
  727. $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user);
  728. if ($result < 0) {
  729. $error++;
  730. }
  731. // End call triggers
  732. }
  733. if (!$error) {
  734. $this->db->commit();
  735. return $this->id;
  736. } else {
  737. $this->db->rollback();
  738. return -4;
  739. }
  740. } else {
  741. $this->error = $langs->trans('FailedToUpdatePrice');
  742. $this->db->rollback();
  743. return -3;
  744. }
  745. } else {
  746. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  747. $this->error = $langs->trans('ErrorRefAlreadyExists');
  748. $this->db->rollback();
  749. return -1;
  750. } else {
  751. $this->error = $this->db->lasterror();
  752. $this->db->rollback();
  753. return -2;
  754. }
  755. }
  756. }
  757. /**
  758. * Load object in memory from database
  759. *
  760. * @param int $id Id supplier invoice
  761. * @param string $ref Ref supplier invoice
  762. * @param string $ref_ext External reference of invoice
  763. * @return int <0 if KO, >0 if OK, 0 if not found
  764. */
  765. public function fetch($id = '', $ref = '', $ref_ext = '')
  766. {
  767. if (empty($id) && empty($ref) && empty($ref_ext)) {
  768. return -1;
  769. }
  770. $sql = "SELECT";
  771. $sql .= " t.rowid,";
  772. $sql .= " t.ref,";
  773. $sql .= " t.ref_supplier,";
  774. $sql .= " t.ref_ext,";
  775. $sql .= " t.entity,";
  776. $sql .= " t.type,";
  777. $sql .= " t.fk_soc,";
  778. $sql .= " t.datec,";
  779. $sql .= " t.datef,";
  780. $sql .= " t.tms,";
  781. $sql .= " t.libelle as label,";
  782. $sql .= " t.paye,";
  783. $sql .= " t.close_code,";
  784. $sql .= " t.close_note,";
  785. $sql .= " t.tva,";
  786. $sql .= " t.localtax1,";
  787. $sql .= " t.localtax2,";
  788. $sql .= " t.total_ht,";
  789. $sql .= " t.total_tva,";
  790. $sql .= " t.total_ttc,";
  791. $sql .= " t.fk_statut as status,";
  792. $sql .= " t.fk_user_author,";
  793. $sql .= " t.fk_user_valid,";
  794. $sql .= " t.fk_facture_source,";
  795. $sql .= " t.vat_reverse_charge,";
  796. $sql .= " t.fk_fac_rec_source,";
  797. $sql .= " t.fk_projet as fk_project,";
  798. $sql .= " t.fk_cond_reglement,";
  799. $sql .= " t.fk_account,";
  800. $sql .= " t.fk_mode_reglement,";
  801. $sql .= " t.date_lim_reglement,";
  802. $sql .= " t.note_private,";
  803. $sql .= " t.note_public,";
  804. $sql .= " t.model_pdf,";
  805. $sql .= " t.import_key,";
  806. $sql .= " t.extraparams,";
  807. $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_label, cr.libelle_facture as cond_reglement_doc,";
  808. $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_label,";
  809. $sql .= ' s.nom as socnom, s.rowid as socid,';
  810. $sql .= ' t.fk_incoterms, t.location_incoterms,';
  811. $sql .= " i.libelle as label_incoterms,";
  812. $sql .= ' t.fk_transport_mode,';
  813. $sql .= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc';
  814. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t';
  815. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)";
  816. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON t.fk_cond_reglement = cr.rowid";
  817. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON t.fk_mode_reglement = p.id";
  818. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid';
  819. if ($id) {
  820. $sql .= " WHERE t.rowid = ".((int) $id);
  821. } else {
  822. $sql .= ' WHERE t.entity IN ('.getEntity('supplier_invoice').')'; // Don't use entity if you use rowid
  823. if ($ref) {
  824. $sql .= " AND t.ref = '".$this->db->escape($ref)."'";
  825. }
  826. if ($ref_ext) {
  827. $sql .= " AND t.ref_ext = '".$this->db->escape($ref_ext)."'";
  828. }
  829. }
  830. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  831. $resql = $this->db->query($sql);
  832. if ($resql) {
  833. if ($this->db->num_rows($resql)) {
  834. $obj = $this->db->fetch_object($resql);
  835. $this->id = $obj->rowid;
  836. $this->ref = $obj->ref ? $obj->ref : $obj->rowid; // We take rowid if ref is empty for backward compatibility
  837. $this->ref_supplier = $obj->ref_supplier;
  838. $this->ref_ext = $obj->ref_ext;
  839. $this->entity = $obj->entity;
  840. $this->type = empty($obj->type) ? self::TYPE_STANDARD : $obj->type;
  841. $this->fk_soc = $obj->fk_soc;
  842. $this->datec = $this->db->jdate($obj->datec);
  843. $this->date = $this->db->jdate($obj->datef);
  844. $this->datep = $this->db->jdate($obj->datef);
  845. $this->tms = $this->db->jdate($obj->tms);
  846. $this->libelle = $obj->label; // deprecated
  847. $this->label = $obj->label;
  848. $this->paye = $obj->paye;
  849. $this->paid = $obj->paye;
  850. $this->close_code = $obj->close_code;
  851. $this->close_note = $obj->close_note;
  852. $this->total_localtax1 = $obj->localtax1;
  853. $this->total_localtax2 = $obj->localtax2;
  854. $this->total_ht = $obj->total_ht;
  855. $this->total_tva = $obj->total_tva;
  856. $this->total_ttc = $obj->total_ttc;
  857. $this->status = $obj->status;
  858. $this->statut = $obj->status; // For backward compatibility
  859. $this->fk_statut = $obj->status; // For backward compatibility
  860. $this->fk_user_author = $obj->fk_user_author;
  861. $this->author = $obj->fk_user_author;
  862. $this->fk_user_valid = $obj->fk_user_valid;
  863. $this->fk_facture_source = $obj->fk_facture_source;
  864. $this->vat_reverse_charge = empty($obj->vat_reverse_charge) ? '0' : '1';
  865. $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
  866. $this->fk_project = $obj->fk_project;
  867. $this->cond_reglement_id = $obj->fk_cond_reglement;
  868. $this->cond_reglement_code = $obj->cond_reglement_code;
  869. $this->cond_reglement = $obj->cond_reglement_label; // deprecated
  870. $this->cond_reglement_label = $obj->cond_reglement_label;
  871. $this->cond_reglement_doc = $obj->cond_reglement_doc;
  872. $this->fk_account = $obj->fk_account;
  873. $this->mode_reglement_id = $obj->fk_mode_reglement;
  874. $this->mode_reglement_code = $obj->mode_reglement_code;
  875. $this->mode_reglement = $obj->mode_reglement_label;
  876. $this->date_echeance = $this->db->jdate($obj->date_lim_reglement);
  877. $this->note = $obj->note_private; // deprecated
  878. $this->note_private = $obj->note_private;
  879. $this->note_public = $obj->note_public;
  880. $this->model_pdf = $obj->model_pdf;
  881. $this->modelpdf = $obj->model_pdf; // deprecated
  882. $this->import_key = $obj->import_key;
  883. //Incoterms
  884. $this->fk_incoterms = $obj->fk_incoterms;
  885. $this->location_incoterms = $obj->location_incoterms;
  886. $this->label_incoterms = $obj->label_incoterms;
  887. $this->transport_mode_id = $obj->fk_transport_mode;
  888. // Multicurrency
  889. $this->fk_multicurrency = $obj->fk_multicurrency;
  890. $this->multicurrency_code = $obj->multicurrency_code;
  891. $this->multicurrency_tx = $obj->multicurrency_tx;
  892. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  893. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  894. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  895. $this->extraparams = (array) json_decode($obj->extraparams, true);
  896. $this->socid = $obj->socid;
  897. $this->socnom = $obj->socnom;
  898. // Retrieve all extrafield
  899. // fetch optionals attributes and labels
  900. $this->fetch_optionals();
  901. if ($this->statut == self::STATUS_DRAFT) {
  902. $this->brouillon = 1;
  903. }
  904. $result = $this->fetch_lines();
  905. if ($result < 0) {
  906. $this->error = $this->db->lasterror();
  907. return -3;
  908. }
  909. } else {
  910. $this->error = 'Bill with id '.$id.' not found';
  911. dol_syslog(get_class($this).'::fetch '.$this->error);
  912. return 0;
  913. }
  914. $this->db->free($resql);
  915. return 1;
  916. } else {
  917. $this->error = "Error ".$this->db->lasterror();
  918. return -1;
  919. }
  920. }
  921. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  922. /**
  923. * Load this->lines
  924. *
  925. * @return int 1 si ok, < 0 si erreur
  926. */
  927. public function fetch_lines()
  928. {
  929. // phpcs:enable
  930. $this->lines = array();
  931. $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.date_start, f.date_end, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.vat_src_code, f.tva_tx';
  932. $sql .= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn, f.fk_remise_except';
  933. $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
  934. $sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
  935. $sql .= ', f.fk_code_ventilation, f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc';
  936. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
  937. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
  938. $sql .= ' WHERE fk_facture_fourn='.((int) $this->id);
  939. $sql .= ' ORDER BY f.rang, f.rowid';
  940. dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
  941. $resql_rows = $this->db->query($sql);
  942. if ($resql_rows) {
  943. $num_rows = $this->db->num_rows($resql_rows);
  944. if ($num_rows) {
  945. $i = 0;
  946. while ($i < $num_rows) {
  947. $obj = $this->db->fetch_object($resql_rows);
  948. $line = new SupplierInvoiceLine($this->db);
  949. $line->id = $obj->rowid;
  950. $line->rowid = $obj->rowid;
  951. $line->description = $obj->description;
  952. $line->date_start = $obj->date_start;
  953. $line->date_end = $obj->date_end;
  954. $line->product_ref = $obj->product_ref;
  955. $line->ref = $obj->product_ref;
  956. $line->ref_supplier = $obj->ref_supplier;
  957. $line->libelle = $obj->label;
  958. $line->label = $obj->label;
  959. $line->product_desc = $obj->product_desc;
  960. $line->subprice = $obj->pu_ht;
  961. $line->pu_ht = $obj->pu_ht;
  962. $line->pu_ttc = $obj->pu_ttc;
  963. $line->vat_src_code = $obj->vat_src_code;
  964. $line->tva_tx = $obj->tva_tx;
  965. $line->localtax1_tx = $obj->localtax1_tx;
  966. $line->localtax2_tx = $obj->localtax2_tx;
  967. $line->localtax1_type = $obj->localtax1_type;
  968. $line->localtax2_type = $obj->localtax2_type;
  969. $line->qty = $obj->qty;
  970. $line->remise_percent = $obj->remise_percent;
  971. $line->fk_remise_except = $obj->fk_remise_except;
  972. //$line->tva = $obj->total_tva; // deprecated
  973. $line->total_ht = $obj->total_ht;
  974. $line->total_ttc = $obj->total_ttc;
  975. $line->total_tva = $obj->total_tva;
  976. $line->total_localtax1 = $obj->total_localtax1;
  977. $line->total_localtax2 = $obj->total_localtax2;
  978. $line->fk_facture_fourn = $obj->fk_facture_fourn;
  979. $line->fk_product = $obj->fk_product;
  980. $line->product_type = $obj->product_type;
  981. $line->product_label = $obj->label;
  982. $line->info_bits = $obj->info_bits;
  983. $line->fk_parent_line = $obj->fk_parent_line;
  984. $line->special_code = $obj->special_code;
  985. $line->rang = $obj->rang;
  986. $line->fk_unit = $obj->fk_unit;
  987. // Accountancy
  988. $line->code_ventilation = $obj->fk_code_ventilation;
  989. $line->fk_accounting_account = $obj->fk_code_ventilation;
  990. // Multicurrency
  991. $line->fk_multicurrency = $obj->fk_multicurrency;
  992. $line->multicurrency_code = $obj->multicurrency_code;
  993. $line->multicurrency_subprice = $obj->multicurrency_subprice;
  994. $line->multicurrency_total_ht = $obj->multicurrency_total_ht;
  995. $line->multicurrency_total_tva = $obj->multicurrency_total_tva;
  996. $line->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  997. // Extra fields
  998. $line->fetch_optionals();
  999. $this->lines[$i] = $line;
  1000. $i++;
  1001. }
  1002. }
  1003. $this->db->free($resql_rows);
  1004. return 1;
  1005. } else {
  1006. $this->error = $this->db->error();
  1007. return -3;
  1008. }
  1009. }
  1010. /**
  1011. * Update database
  1012. *
  1013. * @param User $user User that modify
  1014. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  1015. * @return int <0 if KO, >0 if OK
  1016. */
  1017. public function update($user = null, $notrigger = 0)
  1018. {
  1019. global $conf, $langs;
  1020. $error = 0;
  1021. // Clean parameters
  1022. if (empty($this->type)) {
  1023. $this->type = self::TYPE_STANDARD;
  1024. }
  1025. if (isset($this->ref)) {
  1026. $this->ref = trim($this->ref);
  1027. }
  1028. if (isset($this->ref_supplier)) {
  1029. $this->ref_supplier = trim($this->ref_supplier);
  1030. }
  1031. if (isset($this->ref_ext)) {
  1032. $this->ref_ext = trim($this->ref_ext);
  1033. }
  1034. if (isset($this->entity)) {
  1035. $this->entity = trim($this->entity);
  1036. }
  1037. if (isset($this->type)) {
  1038. $this->type = trim($this->type);
  1039. }
  1040. if (isset($this->fk_soc)) {
  1041. $this->fk_soc = trim($this->fk_soc);
  1042. }
  1043. if (isset($this->label)) {
  1044. $this->label = trim($this->label);
  1045. }
  1046. if (isset($this->libelle)) {
  1047. $this->libelle = trim($this->libelle); // deprecated
  1048. }
  1049. if (isset($this->paye)) {
  1050. $this->paye = trim($this->paye);
  1051. }
  1052. if (isset($this->close_code)) {
  1053. $this->close_code = trim($this->close_code);
  1054. }
  1055. if (isset($this->close_note)) {
  1056. $this->close_note = trim($this->close_note);
  1057. }
  1058. if (isset($this->localtax1)) {
  1059. $this->localtax1 = trim($this->localtax1);
  1060. }
  1061. if (isset($this->localtax2)) {
  1062. $this->localtax2 = trim($this->localtax2);
  1063. }
  1064. if (empty($this->total_ht)) {
  1065. $this->total_ht = 0;
  1066. }
  1067. if (empty($this->total_tva)) {
  1068. $this->total_tva = 0;
  1069. }
  1070. // if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1);
  1071. // if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2);
  1072. if (isset($this->total_ttc)) {
  1073. $this->total_ttc = trim($this->total_ttc);
  1074. }
  1075. if (isset($this->statut)) {
  1076. $this->statut = (int) $this->statut;
  1077. }
  1078. if (isset($this->status)) {
  1079. $this->status = (int) $this->status;
  1080. }
  1081. if (isset($this->author)) {
  1082. $this->author = trim($this->author);
  1083. }
  1084. if (isset($this->fk_user_valid)) {
  1085. $this->fk_user_valid = trim($this->fk_user_valid);
  1086. }
  1087. if (isset($this->fk_facture_source)) {
  1088. $this->fk_facture_source = trim($this->fk_facture_source);
  1089. }
  1090. if (isset($this->fk_project)) {
  1091. if (empty($this->fk_project)) $this->fk_project = null;
  1092. else $this->fk_project = intval($this->fk_project);
  1093. }
  1094. if (isset($this->cond_reglement_id)) {
  1095. $this->cond_reglement_id = trim($this->cond_reglement_id);
  1096. }
  1097. if (isset($this->note_private)) {
  1098. $this->note = trim($this->note_private);
  1099. }
  1100. if (isset($this->note_public)) {
  1101. $this->note_public = trim($this->note_public);
  1102. }
  1103. if (isset($this->model_pdf)) {
  1104. $this->model_pdf = trim($this->model_pdf);
  1105. }
  1106. if (isset($this->import_key)) {
  1107. $this->import_key = trim($this->import_key);
  1108. }
  1109. // Check parameters
  1110. // Put here code to add control on parameters values
  1111. // Update request
  1112. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn SET";
  1113. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
  1114. $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
  1115. $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
  1116. $sql .= " entity=".(isset($this->entity) ? ((int) $this->entity) : "null").",";
  1117. $sql .= " type=".(isset($this->type) ? ((int) $this->type) : "null").",";
  1118. $sql .= " fk_soc=".(isset($this->fk_soc) ? ((int) $this->fk_soc) : "null").",";
  1119. $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
  1120. $sql .= " datef=".(dol_strlen($this->date) != 0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
  1121. if (dol_strlen($this->tms) != 0) {
  1122. $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
  1123. }
  1124. $sql .= " libelle=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
  1125. $sql .= " paye=".(isset($this->paye) ? ((int) $this->paye) : "null").",";
  1126. $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
  1127. $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
  1128. $sql .= " localtax1=".(isset($this->localtax1) ? ((float) $this->localtax1) : "null").",";
  1129. $sql .= " localtax2=".(isset($this->localtax2) ? ((float) $this->localtax2) : "null").",";
  1130. $sql .= " total_ht=".(isset($this->total_ht) ? ((float) $this->total_ht) : "null").",";
  1131. $sql .= " total_tva=".(isset($this->total_tva) ? ((float) $this->total_tva) : "null").",";
  1132. $sql .= " total_ttc=".(isset($this->total_ttc) ? ((float) $this->total_ttc) : "null").",";
  1133. $sql .= " fk_statut=".(isset($this->status) ? ((int) $this->status) : (isset($this->statut) ? ((int) $this->statut) : "null")).",";
  1134. $sql .= " fk_user_author=".(isset($this->author) ? ((int) $this->author) : "null").",";
  1135. $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? ((int) $this->fk_user_valid) : "null").",";
  1136. $sql .= " fk_facture_source=".($this->fk_facture_source ? ((int) $this->fk_facture_source) : "null").",";
  1137. $sql .= " vat_reverse_charge = ".($this->vat_reverse_charge != '' ? ((int) $this->db->escape($this->vat_reverse_charge)) : 0).",";
  1138. $sql .= " fk_projet=".(isset($this->fk_project) ? ((int) $this->fk_project) : "null").",";
  1139. $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? ((int) $this->cond_reglement_id) : "null").",";
  1140. $sql .= " date_lim_reglement=".(dol_strlen($this->date_echeance) != 0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
  1141. $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
  1142. $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
  1143. $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
  1144. $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
  1145. $sql .= " WHERE rowid=".((int) $this->id);
  1146. $this->db->begin();
  1147. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  1148. $resql = $this->db->query($sql);
  1149. if (!$resql) {
  1150. $error++;
  1151. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1152. $this->errors[] = $langs->trans('ErrorRefAlreadyExists');
  1153. } else {
  1154. $this->errors[] = "Error ".$this->db->lasterror();
  1155. }
  1156. }
  1157. if (!$error) {
  1158. $result = $this->insertExtraFields();
  1159. if ($result < 0) {
  1160. $error++;
  1161. }
  1162. }
  1163. if (!$error) {
  1164. if (!$notrigger) {
  1165. // Call trigger
  1166. $result = $this->call_trigger('BILL_SUPPLIER_MODIFY', $user);
  1167. if ($result < 0) {
  1168. $error++;
  1169. }
  1170. // End call triggers
  1171. }
  1172. }
  1173. // Commit or rollback
  1174. if ($error) {
  1175. foreach ($this->errors as $errmsg) {
  1176. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  1177. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1178. }
  1179. $this->db->rollback();
  1180. return -1 * $error;
  1181. } else {
  1182. $this->db->commit();
  1183. return 1;
  1184. }
  1185. }
  1186. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1187. /**
  1188. * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount)
  1189. *
  1190. * @param int $idremise Id of absolute discount
  1191. * @return int >0 if OK, <0 if KO
  1192. */
  1193. public function insert_discount($idremise)
  1194. {
  1195. // phpcs:enable
  1196. global $conf, $langs;
  1197. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1198. include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  1199. $this->db->begin();
  1200. $remise = new DiscountAbsolute($this->db);
  1201. $result = $remise->fetch($idremise);
  1202. if ($result > 0) {
  1203. if ($remise->fk_invoice_supplier) { // Protection against multiple submission
  1204. $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
  1205. $this->db->rollback();
  1206. return -5;
  1207. }
  1208. $facligne = new SupplierInvoiceLine($this->db);
  1209. $facligne->fk_facture_fourn = $this->id;
  1210. $facligne->fk_remise_except = $remise->id;
  1211. $facligne->desc = $remise->description; // Description ligne
  1212. $facligne->vat_src_code = $remise->vat_src_code;
  1213. $facligne->tva_tx = $remise->tva_tx;
  1214. $facligne->subprice = -$remise->amount_ht;
  1215. $facligne->fk_product = 0; // Id produit predefini
  1216. $facligne->product_type = 0;
  1217. $facligne->qty = 1;
  1218. $facligne->remise_percent = 0;
  1219. $facligne->rang = -1;
  1220. $facligne->info_bits = 2;
  1221. if (!empty($conf->global->MAIN_ADD_LINE_AT_POSITION)) {
  1222. $facligne->rang = 1;
  1223. $linecount = count($this->lines);
  1224. for ($ii = 1; $ii <= $linecount; $ii++) {
  1225. $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii+1);
  1226. }
  1227. }
  1228. // Get buy/cost price of invoice that is source of discount
  1229. if ($remise->fk_invoice_supplier_source > 0) {
  1230. $srcinvoice = new FactureFournisseur($this->db);
  1231. $srcinvoice->fetch($remise->fk_invoice_supplier_source);
  1232. $totalcostpriceofinvoice = 0;
  1233. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
  1234. $formmargin = new FormMargin($this->db);
  1235. $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
  1236. $facligne->pa_ht = $arraytmp['pa_total'];
  1237. }
  1238. $facligne->total_ht = -$remise->amount_ht;
  1239. $facligne->total_tva = -$remise->amount_tva;
  1240. $facligne->total_ttc = -$remise->amount_ttc;
  1241. $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
  1242. $facligne->multicurrency_total_ht = -$remise->multicurrency_total_ht;
  1243. $facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva;
  1244. $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc;
  1245. $lineid = $facligne->insert();
  1246. if ($lineid > 0) {
  1247. $result = $this->update_price(1);
  1248. if ($result > 0) {
  1249. // Create link between discount and invoice line
  1250. $result = $remise->link_to_invoice($lineid, 0);
  1251. if ($result < 0) {
  1252. $this->error = $remise->error;
  1253. $this->db->rollback();
  1254. return -4;
  1255. }
  1256. $this->db->commit();
  1257. return 1;
  1258. } else {
  1259. $this->error = $facligne->error;
  1260. $this->db->rollback();
  1261. return -1;
  1262. }
  1263. } else {
  1264. $this->error = $facligne->error;
  1265. $this->db->rollback();
  1266. return -2;
  1267. }
  1268. } else {
  1269. $this->db->rollback();
  1270. return -3;
  1271. }
  1272. }
  1273. /**
  1274. * Delete invoice from database
  1275. *
  1276. * @param User $user User object
  1277. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1278. * @return int <0 if KO, >0 if OK
  1279. */
  1280. public function delete(User $user, $notrigger = 0)
  1281. {
  1282. global $langs, $conf;
  1283. $rowid = $this->id;
  1284. dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG);
  1285. // TODO Test if there is at least on payment. If yes, refuse to delete.
  1286. $error = 0;
  1287. $this->db->begin();
  1288. if (!$error && !$notrigger) {
  1289. // Call trigger
  1290. $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user);
  1291. if ($result < 0) {
  1292. $this->db->rollback();
  1293. return -1;
  1294. }
  1295. // Fin appel triggers
  1296. }
  1297. if (!$error) {
  1298. // If invoice was converted into a discount not yet consumed, we remove discount
  1299. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
  1300. $sql .= ' WHERE fk_invoice_supplier_source = '.((int) $rowid);
  1301. $sql .= ' AND fk_invoice_supplier_line IS NULL';
  1302. $resql = $this->db->query($sql);
  1303. // If invoice has consumned discounts
  1304. $this->fetch_lines();
  1305. $list_rowid_det = array();
  1306. foreach ($this->lines as $key => $invoiceline) {
  1307. $list_rowid_det[] = $invoiceline->rowid;
  1308. }
  1309. // Consumned discounts are freed
  1310. if (count($list_rowid_det)) {
  1311. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  1312. $sql .= ' SET fk_invoice_supplier = NULL, fk_invoice_supplier_line = NULL';
  1313. $sql .= ' WHERE fk_invoice_supplier_line IN ('.$this->db->sanitize(join(',', $list_rowid_det)).')';
  1314. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1315. if (!$this->db->query($sql)) {
  1316. $error++;
  1317. }
  1318. }
  1319. }
  1320. if (!$error) {
  1321. $main = MAIN_DB_PREFIX.'facture_fourn_det';
  1322. $ef = $main."_extrafields";
  1323. $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture_fourn = ".((int) $rowid).")";
  1324. $resqlef = $this->db->query($sqlef);
  1325. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.((int) $rowid);
  1326. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1327. $resql = $this->db->query($sql);
  1328. if ($resqlef && $resql) {
  1329. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.((int) $rowid);
  1330. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1331. $resql2 = $this->db->query($sql);
  1332. if (!$resql2) {
  1333. $error++;
  1334. }
  1335. } else {
  1336. $error++;
  1337. }
  1338. }
  1339. if (!$error) {
  1340. // Delete linked object
  1341. $res = $this->deleteObjectLinked();
  1342. if ($res < 0) {
  1343. $error++;
  1344. }
  1345. }
  1346. if (!$error) {
  1347. // Delete linked object
  1348. $res = $this->deleteObjectLinked();
  1349. if ($res < 0) {
  1350. $error++;
  1351. }
  1352. }
  1353. if (!$error) {
  1354. // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
  1355. $this->deleteEcmFiles();
  1356. // We remove directory
  1357. if ($conf->fournisseur->facture->dir_output) {
  1358. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1359. $ref = dol_sanitizeFileName($this->ref);
  1360. $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$ref;
  1361. $file = $dir."/".$ref.".pdf";
  1362. if (file_exists($file)) {
  1363. if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
  1364. $this->error = 'ErrorFailToDeleteFile';
  1365. $error++;
  1366. }
  1367. }
  1368. if (file_exists($dir)) {
  1369. $res = @dol_delete_dir_recursive($dir);
  1370. if (!$res) {
  1371. $this->error = 'ErrorFailToDeleteDir';
  1372. $error++;
  1373. }
  1374. }
  1375. }
  1376. }
  1377. // Remove extrafields
  1378. if (!$error) {
  1379. $result = $this->deleteExtraFields();
  1380. if ($result < 0) {
  1381. $error++;
  1382. dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
  1383. }
  1384. }
  1385. if (!$error) {
  1386. dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
  1387. $this->db->commit();
  1388. return 1;
  1389. } else {
  1390. $this->error = $this->db->lasterror();
  1391. $this->db->rollback();
  1392. return -$error;
  1393. }
  1394. }
  1395. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1396. /**
  1397. * Tag invoice as a paid invoice
  1398. *
  1399. * @deprecated
  1400. * @see setPaid()
  1401. * @param User $user Object user
  1402. * @param string $close_code Code indicates whether the class has paid in full while payment is incomplete. Not implementd yet.
  1403. * @param string $close_note Comment informs if the class has been paid while payment is incomplete. Not implementd yet.
  1404. * @return int <0 si ko, >0 si ok
  1405. */
  1406. public function set_paid($user, $close_code = '', $close_note = '')
  1407. {
  1408. // phpcs:enable
  1409. dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
  1410. return $this->setPaid($user, $close_code, $close_note);
  1411. }
  1412. /**
  1413. * Tag invoice as a paid invoice
  1414. *
  1415. * @param User $user Object user
  1416. * @param string $close_code Code indicates whether the class has paid in full while payment is incomplete. Not implementd yet.
  1417. * @param string $close_note Comment informs if the class has been paid while payment is incomplete. Not implementd yet.
  1418. * @return int <0 si ko, >0 si ok
  1419. */
  1420. public function setPaid($user, $close_code = '', $close_note = '')
  1421. {
  1422. $error = 0;
  1423. if ($this->paye != 1) {
  1424. $this->db->begin();
  1425. $now = dol_now();
  1426. dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG);
  1427. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn SET';
  1428. $sql .= ' fk_statut = '.self::STATUS_CLOSED;
  1429. if (!$close_code) {
  1430. $sql .= ', paye=1';
  1431. }
  1432. if ($close_code) {
  1433. $sql .= ", close_code='".$this->db->escape($close_code)."'";
  1434. }
  1435. if ($close_note) {
  1436. $sql .= ", close_note='".$this->db->escape($close_note)."'";
  1437. }
  1438. $sql .= ', fk_user_closing = '.((int) $user->id);
  1439. $sql .= ", date_closing = '".$this->db->idate($now)."'";
  1440. $sql .= ' WHERE rowid = '.((int) $this->id);
  1441. $resql = $this->db->query($sql);
  1442. if ($resql) {
  1443. // Call trigger
  1444. $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user);
  1445. if ($result < 0) {
  1446. $error++;
  1447. }
  1448. // End call triggers
  1449. } else {
  1450. $error++;
  1451. $this->error = $this->db->error();
  1452. dol_print_error($this->db);
  1453. }
  1454. if (!$error) {
  1455. $this->db->commit();
  1456. return 1;
  1457. } else {
  1458. $this->db->rollback();
  1459. return -1;
  1460. }
  1461. } else {
  1462. return 0;
  1463. }
  1464. }
  1465. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1466. /**
  1467. * Tag the invoice as not fully paid + trigger call BILL_UNPAYED
  1468. * Function used when a direct debit payment is refused,
  1469. * or when the invoice was canceled and reopened.
  1470. *
  1471. * @deprecated
  1472. * @see setUnpaid()
  1473. * @param User $user Object user that change status
  1474. * @return int <0 si ok, >0 si ok
  1475. */
  1476. public function set_unpaid($user)
  1477. {
  1478. // phpcs:enable
  1479. dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
  1480. return $this->setUnpaid($user);
  1481. }
  1482. /**
  1483. * Tag the invoice as not fully paid + trigger call BILL_UNPAYED
  1484. * Function used when a direct debit payment is refused,
  1485. * or when the invoice was canceled and reopened.
  1486. *
  1487. * @param User $user Object user that change status
  1488. * @return int <0 si ok, >0 si ok
  1489. */
  1490. public function setUnpaid($user)
  1491. {
  1492. $error = 0;
  1493. $this->db->begin();
  1494. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
  1495. $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
  1496. $sql .= ' date_closing=null,';
  1497. $sql .= ' fk_user_closing=null';
  1498. $sql .= ' WHERE rowid = '.((int) $this->id);
  1499. dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
  1500. $resql = $this->db->query($sql);
  1501. if ($resql) {
  1502. // Call trigger
  1503. $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user);
  1504. if ($result < 0) {
  1505. $error++;
  1506. }
  1507. // End call triggers
  1508. } else {
  1509. $error++;
  1510. $this->error = $this->db->error();
  1511. dol_print_error($this->db);
  1512. }
  1513. if (!$error) {
  1514. $this->db->commit();
  1515. return 1;
  1516. } else {
  1517. $this->db->rollback();
  1518. return -1;
  1519. }
  1520. }
  1521. /**
  1522. * Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never received) + call trigger BILL_CANCEL
  1523. * Warning, if option to decrease stock on invoice was set, this function does not change stock (it might be a cancel because
  1524. * of no payment even if merchandises were sent).
  1525. *
  1526. * @param User $user Object user making change
  1527. * @param string $close_code Code of closing invoice (CLOSECODE_REPLACED, CLOSECODE_...)
  1528. * @param string $close_note Comment
  1529. * @return int <0 if KO, >0 if OK
  1530. */
  1531. public function setCanceled($user, $close_code = '', $close_note = '')
  1532. {
  1533. dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
  1534. $this->db->begin();
  1535. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn SET';
  1536. $sql .= ' fk_statut='.self::STATUS_ABANDONED;
  1537. if ($close_code) {
  1538. $sql .= ", close_code='".$this->db->escape($close_code)."'";
  1539. }
  1540. if ($close_note) {
  1541. $sql .= ", close_note='".$this->db->escape($close_note)."'";
  1542. }
  1543. $sql .= " WHERE rowid = ".((int) $this->id);
  1544. $resql = $this->db->query($sql);
  1545. if ($resql) {
  1546. // Bound discounts are deducted from the invoice
  1547. // as they have not been used since the invoice is abandoned.
  1548. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  1549. $sql .= ' SET fk_invoice_supplier = NULL';
  1550. $sql .= ' WHERE fk_invoice_supplier = '.((int) $this->id);
  1551. $resql = $this->db->query($sql);
  1552. if ($resql) {
  1553. // Call trigger
  1554. $result = $this->call_trigger('BILL_SUPPLIER_CANCEL', $user);
  1555. if ($result < 0) {
  1556. $this->db->rollback();
  1557. return -1;
  1558. }
  1559. // End call triggers
  1560. $this->db->commit();
  1561. return 1;
  1562. } else {
  1563. $this->error = $this->db->error()." sql=".$sql;
  1564. $this->db->rollback();
  1565. return -1;
  1566. }
  1567. } else {
  1568. $this->error = $this->db->error()." sql=".$sql;
  1569. $this->db->rollback();
  1570. return -2;
  1571. }
  1572. }
  1573. /**
  1574. * Tag invoice as validated + call trigger BILL_VALIDATE
  1575. *
  1576. * @param User $user Object user that validate
  1577. * @param string $force_number Reference to force on invoice
  1578. * @param int $idwarehouse Id of warehouse for stock change
  1579. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1580. * @return int <0 if KO, =0 if nothing to do, >0 if OK
  1581. */
  1582. public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0)
  1583. {
  1584. global $conf, $langs;
  1585. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1586. $now = dol_now();
  1587. $error = 0;
  1588. dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
  1589. // Force to have object complete for checks
  1590. $this->fetch_thirdparty();
  1591. $this->fetch_lines();
  1592. // Check parameters
  1593. if ($this->statut > self::STATUS_DRAFT) { // This is to avoid to validate twice (avoid errors on logs and stock management)
  1594. dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
  1595. return 0;
  1596. }
  1597. if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier)) {
  1598. $langs->load("errors");
  1599. $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
  1600. return -1;
  1601. }
  1602. if (count($this->lines) <= 0) {
  1603. $langs->load("errors");
  1604. $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
  1605. return -1;
  1606. }
  1607. $this->db->begin();
  1608. // Define new ref
  1609. if ($force_number) {
  1610. $num = $force_number;
  1611. } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
  1612. $num = $this->getNextNumRef($this->thirdparty);
  1613. } else {
  1614. $num = $this->ref;
  1615. }
  1616. $this->newref = dol_sanitizeFileName($num);
  1617. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
  1618. $sql .= " SET ref='".$this->db->escape($num)."', fk_statut = 1, fk_user_valid = ".((int) $user->id).", date_valid = '".$this->db->idate($now)."'";
  1619. $sql .= " WHERE rowid = ".((int) $this->id);
  1620. dol_syslog(get_class($this)."::validate", LOG_DEBUG);
  1621. $resql = $this->db->query($sql);
  1622. if ($resql) {
  1623. // Si on incrémente le produit principal et ses composants à la validation de facture fournisseur
  1624. if (!$error && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
  1625. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1626. $langs->load("agenda");
  1627. $cpt = count($this->lines);
  1628. for ($i = 0; $i < $cpt; $i++) {
  1629. if ($this->lines[$i]->fk_product > 0) {
  1630. $mouvP = new MouvementStock($this->db);
  1631. $mouvP->origin = &$this;
  1632. $mouvP->setOrigin($this->element, $this->id);
  1633. // We increase stock for product
  1634. $up_ht_disc = $this->lines[$i]->subprice;
  1635. if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) {
  1636. $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
  1637. }
  1638. if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  1639. $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num));
  1640. } else {
  1641. $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num));
  1642. }
  1643. if ($result < 0) {
  1644. $error++;
  1645. }
  1646. }
  1647. }
  1648. }
  1649. // Triggers call
  1650. if (!$error && empty($notrigger)) {
  1651. // Call trigger
  1652. $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user);
  1653. if ($result < 0) {
  1654. $error++;
  1655. }
  1656. // End call triggers
  1657. }
  1658. if (!$error) {
  1659. $this->oldref = $this->ref;
  1660. // Rename directory if dir was a temporary ref
  1661. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  1662. // Now we rename also files into index
  1663. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->newref)."'";
  1664. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  1665. $resql = $this->db->query($sql);
  1666. if (!$resql) {
  1667. $error++; $this->error = $this->db->lasterror();
  1668. }
  1669. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  1670. $oldref = dol_sanitizeFileName($this->ref);
  1671. $newref = dol_sanitizeFileName($num);
  1672. $dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$oldref;
  1673. $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$newref;
  1674. if (!$error && file_exists($dirsource)) {
  1675. dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
  1676. if (@rename($dirsource, $dirdest)) {
  1677. dol_syslog("Rename ok");
  1678. // Rename docs starting with $oldref with $newref
  1679. $listoffiles = dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  1680. foreach ($listoffiles as $fileentry) {
  1681. $dirsource = $fileentry['name'];
  1682. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  1683. $dirsource = $fileentry['path'].'/'.$dirsource;
  1684. $dirdest = $fileentry['path'].'/'.$dirdest;
  1685. @rename($dirsource, $dirdest);
  1686. }
  1687. }
  1688. }
  1689. }
  1690. }
  1691. // Set new ref and define current statut
  1692. if (!$error) {
  1693. $this->ref = $num;
  1694. $this->statut = self::STATUS_VALIDATED;
  1695. //$this->date_validation=$now; this is stored into log table
  1696. }
  1697. if (!$error) {
  1698. $this->db->commit();
  1699. return 1;
  1700. } else {
  1701. $this->db->rollback();
  1702. return -1;
  1703. }
  1704. } else {
  1705. $this->error = $this->db->error();
  1706. $this->db->rollback();
  1707. return -1;
  1708. }
  1709. }
  1710. /**
  1711. * Set draft status
  1712. *
  1713. * @param User $user Object user that modify
  1714. * @param int $idwarehouse Id warehouse to use for stock change.
  1715. * @return int <0 if KO, >0 if OK
  1716. */
  1717. public function setDraft($user, $idwarehouse = -1)
  1718. {
  1719. // phpcs:enable
  1720. global $conf, $langs;
  1721. $error = 0;
  1722. if ($this->statut == self::STATUS_DRAFT) {
  1723. dol_syslog(__METHOD__." already draft status", LOG_WARNING);
  1724. return 0;
  1725. }
  1726. dol_syslog(__METHOD__, LOG_DEBUG);
  1727. $this->db->begin();
  1728. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
  1729. $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
  1730. $sql .= " WHERE rowid = ".((int) $this->id);
  1731. $result = $this->db->query($sql);
  1732. if ($result) {
  1733. if (!$error) {
  1734. $this->oldcopy = clone $this;
  1735. }
  1736. // Si on incremente le produit principal et ses composants a la validation de facture fournisseur, on decremente
  1737. if ($result >= 0 && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
  1738. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1739. $langs->load("agenda");
  1740. $cpt = count($this->lines);
  1741. for ($i = 0; $i < $cpt; $i++) {
  1742. if ($this->lines[$i]->fk_product > 0) {
  1743. $mouvP = new MouvementStock($this->db);
  1744. $mouvP->origin = &$this;
  1745. $mouvP->setOrigin($this->element, $this->id);
  1746. // We increase stock for product
  1747. if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  1748. $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
  1749. } else {
  1750. $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
  1751. }
  1752. }
  1753. }
  1754. }
  1755. // Triggers call
  1756. if (!$error && empty($notrigger)) {
  1757. // Call trigger
  1758. $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user);
  1759. if ($result < 0) {
  1760. $error++;
  1761. }
  1762. // End call triggers
  1763. }
  1764. if ($error == 0) {
  1765. $this->db->commit();
  1766. return 1;
  1767. } else {
  1768. $this->db->rollback();
  1769. return -1;
  1770. }
  1771. } else {
  1772. $this->error = $this->db->error();
  1773. $this->db->rollback();
  1774. return -1;
  1775. }
  1776. }
  1777. /**
  1778. * Adds an invoice line (associated with no predefined product/service)
  1779. * The parameters are already supposed to be correct and with final values when calling
  1780. * this method. Also, for the VAT rate, it must already have been defined by the caller by
  1781. * by the get_default_tva method(vendor_company, buying company, idprod) and the desc must
  1782. * already have the right value (the caller has to manage the multilanguage).
  1783. *
  1784. * @param string $desc Description of the line
  1785. * @param double $pu Unit price (HT or TTC according to price_base_type, > 0 even for credit note)
  1786. * @param double $txtva Force Vat rate to use, -1 for auto.
  1787. * @param double $txlocaltax1 LocalTax1 Rate
  1788. * @param double $txlocaltax2 LocalTax2 Rate
  1789. * @param double $qty Quantity
  1790. * @param int $fk_product Product/Service ID predefined
  1791. * @param double $remise_percent Percentage discount of the line
  1792. * @param integer $date_start Service start date
  1793. * @param integer $date_end Service expiry date
  1794. * @param string $ventil Accounting breakdown code
  1795. * @param int $info_bits Line type bits
  1796. * @param string $price_base_type HT or TTC
  1797. * @param int $type Type of line (0=product, 1=service)
  1798. * @param int $rang Position of line
  1799. * @param int $notrigger Disable triggers
  1800. * @param array $array_options extrafields array
  1801. * @param string $fk_unit Code of the unit to use. Null to use the default one
  1802. * @param int $origin_id id origin document
  1803. * @param double $pu_devise Amount in currency
  1804. * @param string $ref_supplier Supplier ref
  1805. * @param string $special_code Special code
  1806. * @param int $fk_parent_line Parent line id
  1807. * @param int $fk_remise_except Id discount used
  1808. * @return int >0 if OK, <0 if KO
  1809. */
  1810. public function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product = 0, $remise_percent = 0, $date_start = '', $date_end = '', $ventil = 0, $info_bits = '', $price_base_type = 'HT', $type = 0, $rang = -1, $notrigger = false, $array_options = 0, $fk_unit = null, $origin_id = 0, $pu_devise = 0, $ref_supplier = '', $special_code = '', $fk_parent_line = 0, $fk_remise_except = 0)
  1811. {
  1812. global $langs, $mysoc, $conf;
  1813. dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$ventil,$info_bits,$price_base_type,$type,$fk_unit,fk_remise_except=$fk_remise_except", LOG_DEBUG);
  1814. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1815. if ($this->statut == self::STATUS_DRAFT) {
  1816. // Clean parameters
  1817. if (empty($remise_percent)) {
  1818. $remise_percent = 0;
  1819. }
  1820. if (empty($qty)) {
  1821. $qty = 0;
  1822. }
  1823. if (empty($info_bits)) {
  1824. $info_bits = 0;
  1825. }
  1826. if (empty($rang)) {
  1827. $rang = 0;
  1828. }
  1829. if (empty($ventil)) {
  1830. $ventil = 0;
  1831. }
  1832. if (empty($txtva)) {
  1833. $txtva = 0;
  1834. }
  1835. if (empty($txlocaltax1)) {
  1836. $txlocaltax1 = 0;
  1837. }
  1838. if (empty($txlocaltax2)) {
  1839. $txlocaltax2 = 0;
  1840. }
  1841. $remise_percent = price2num($remise_percent);
  1842. $qty = price2num($qty);
  1843. $pu = price2num($pu);
  1844. if (!preg_match('/\((.*)\)/', $txtva)) {
  1845. $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
  1846. }
  1847. $txlocaltax1 = price2num($txlocaltax1);
  1848. $txlocaltax2 = price2num($txlocaltax2);
  1849. if ($date_start && $date_end && $date_start > $date_end) {
  1850. $langs->load("errors");
  1851. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  1852. return -1;
  1853. }
  1854. $this->db->begin();
  1855. if ($fk_product > 0) {
  1856. if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) {
  1857. // Check quantity is enough
  1858. dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." qty=".$qty." ref_supplier=".$ref_supplier);
  1859. $prod = new ProductFournisseur($this->db);
  1860. if ($prod->fetch($fk_product) > 0) {
  1861. $product_type = $prod->type;
  1862. $label = $prod->label;
  1863. $fk_prod_fourn_price = 0;
  1864. // We use 'none' instead of $ref_supplier, because $ref_supplier may not exists anymore. So we will take the first supplier price ok.
  1865. // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
  1866. $result = $prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', ($this->fk_soc ? $this->fk_soc : $this->socid)); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$ref_supplier/$this->fk_soc
  1867. if ($result > 0) {
  1868. if (empty($pu)) {
  1869. $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice
  1870. }
  1871. $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice
  1872. // is remise percent not keyed but present for the product we add it
  1873. if ($remise_percent == 0 && $prod->remise_percent != 0) {
  1874. $remise_percent = $prod->remise_percent;
  1875. }
  1876. }
  1877. if ($result == 0) { // If result == 0, we failed to found the supplier reference price
  1878. $langs->load("errors");
  1879. $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
  1880. $this->db->rollback();
  1881. dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
  1882. //$pu = $prod->fourn_pu; // We do not overwrite unit price
  1883. //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price
  1884. return -1;
  1885. }
  1886. if ($result == -1) {
  1887. $langs->load("errors");
  1888. $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
  1889. $this->db->rollback();
  1890. dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
  1891. return -1;
  1892. }
  1893. if ($result < -1) {
  1894. $this->error = $prod->error;
  1895. $this->db->rollback();
  1896. dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
  1897. return -1;
  1898. }
  1899. } else {
  1900. $this->error = $prod->error;
  1901. $this->db->rollback();
  1902. return -1;
  1903. }
  1904. }
  1905. } else {
  1906. $product_type = $type;
  1907. }
  1908. if (isModEnabled("multicurrency") && $pu_devise > 0) {
  1909. $pu = 0;
  1910. }
  1911. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
  1912. // Clean vat code
  1913. $reg = array();
  1914. $vat_src_code = '';
  1915. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  1916. $vat_src_code = $reg[1];
  1917. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  1918. }
  1919. // Calcul du total TTC et de la TVA pour la ligne a partir de
  1920. // qty, pu, remise_percent et txtva
  1921. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  1922. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  1923. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_devise);
  1924. $total_ht = $tabprice[0];
  1925. $total_tva = $tabprice[1];
  1926. $total_ttc = $tabprice[2];
  1927. $total_localtax1 = $tabprice[9];
  1928. $total_localtax2 = $tabprice[10];
  1929. $pu_ht = $tabprice[3];
  1930. // MultiCurrency
  1931. $multicurrency_total_ht = $tabprice[16];
  1932. $multicurrency_total_tva = $tabprice[17];
  1933. $multicurrency_total_ttc = $tabprice[18];
  1934. $pu_ht_devise = $tabprice[19];
  1935. // Check parameters
  1936. if ($type < 0) {
  1937. return -1;
  1938. }
  1939. if ($rang < 0) {
  1940. $rangmax = $this->line_max();
  1941. $rang = $rangmax + 1;
  1942. }
  1943. // Insert line
  1944. $supplierinvoiceline = new SupplierInvoiceLine($this->db);
  1945. $supplierinvoiceline->context = $this->context;
  1946. $supplierinvoiceline->fk_facture_fourn = $this->id;
  1947. //$supplierinvoiceline->label=$label; // deprecated
  1948. $supplierinvoiceline->desc = $desc;
  1949. $supplierinvoiceline->ref_supplier = $ref_supplier;
  1950. $supplierinvoiceline->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
  1951. $supplierinvoiceline->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
  1952. $supplierinvoiceline->vat_src_code = $vat_src_code;
  1953. $supplierinvoiceline->tva_tx = $txtva;
  1954. $supplierinvoiceline->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
  1955. $supplierinvoiceline->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
  1956. $supplierinvoiceline->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  1957. $supplierinvoiceline->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  1958. $supplierinvoiceline->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
  1959. $supplierinvoiceline->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
  1960. $supplierinvoiceline->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
  1961. $supplierinvoiceline->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
  1962. $supplierinvoiceline->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
  1963. $supplierinvoiceline->fk_product = $fk_product;
  1964. $supplierinvoiceline->product_type = $type;
  1965. $supplierinvoiceline->remise_percent = $remise_percent;
  1966. $supplierinvoiceline->date_start = $date_start;
  1967. $supplierinvoiceline->date_end = $date_end;
  1968. $supplierinvoiceline->fk_code_ventilation = $ventil;
  1969. $supplierinvoiceline->rang = $rang;
  1970. $supplierinvoiceline->info_bits = $info_bits;
  1971. $supplierinvoiceline->fk_remise_except = $fk_remise_except;
  1972. $supplierinvoiceline->special_code = ((string) $special_code != '' ? $special_code : $this->special_code);
  1973. $supplierinvoiceline->fk_parent_line = $fk_parent_line;
  1974. $supplierinvoiceline->origin = $this->origin;
  1975. $supplierinvoiceline->origin_id = $origin_id;
  1976. $supplierinvoiceline->fk_unit = $fk_unit;
  1977. // Multicurrency
  1978. $supplierinvoiceline->fk_multicurrency = $this->fk_multicurrency;
  1979. $supplierinvoiceline->multicurrency_code = $this->multicurrency_code;
  1980. $supplierinvoiceline->multicurrency_subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise
  1981. $supplierinvoiceline->multicurrency_total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht); // For credit note and if qty is negative, total is negative
  1982. $supplierinvoiceline->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva); // For credit note and if qty is negative, total is negative
  1983. $supplierinvoiceline->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc); // For credit note and if qty is negative, total is negative
  1984. if (is_array($array_options) && count($array_options) > 0) {
  1985. $supplierinvoiceline->array_options = $array_options;
  1986. }
  1987. $result = $supplierinvoiceline->insert($notrigger);
  1988. if ($result > 0) {
  1989. // Reorder if child line
  1990. if (!empty($fk_parent_line)) {
  1991. $this->line_order(true, 'DESC');
  1992. } elseif ($rang > 0 && $rang <= count($this->lines)) { // Update all rank of all other lines
  1993. $linecount = count($this->lines);
  1994. for ($ii = $rang; $ii <= $linecount; $ii++) {
  1995. $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
  1996. }
  1997. }
  1998. // Mise a jour informations denormalisees au niveau de la facture meme
  1999. $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
  2000. if ($result > 0) {
  2001. $this->db->commit();
  2002. return $supplierinvoiceline->id;
  2003. } else {
  2004. $this->error = $this->db->error();
  2005. $this->db->rollback();
  2006. return -1;
  2007. }
  2008. } else {
  2009. $this->error = $supplierinvoiceline->error;
  2010. $this->errors = $supplierinvoiceline->errors;
  2011. $this->db->rollback();
  2012. return -2;
  2013. }
  2014. } else {
  2015. return 0;
  2016. }
  2017. }
  2018. /**
  2019. * Update a line detail into database
  2020. *
  2021. * @param int $id Id of line invoice
  2022. * @param string $desc Description of line
  2023. * @param double $pu Prix unitaire (HT ou TTC selon price_base_type)
  2024. * @param double $vatrate VAT Rate (Can be '8.5', '8.5 (ABC)')
  2025. * @param double $txlocaltax1 LocalTax1 Rate
  2026. * @param double $txlocaltax2 LocalTax2 Rate
  2027. * @param double $qty Quantity
  2028. * @param int $idproduct Id produit
  2029. * @param double $price_base_type HT or TTC
  2030. * @param int $info_bits Miscellaneous informations of line
  2031. * @param int $type Type of line (0=product, 1=service)
  2032. * @param double $remise_percent Percentage discount of the line
  2033. * @param int $notrigger Disable triggers
  2034. * @param integer $date_start Date start of service
  2035. * @param integer $date_end Date end of service
  2036. * @param array $array_options extrafields array
  2037. * @param string $fk_unit Code of the unit to use. Null to use the default one
  2038. * @param double $pu_devise Amount in currency
  2039. * @param string $ref_supplier Supplier ref
  2040. * @param integer $rang line rank
  2041. * @return int <0 if KO, >0 if OK
  2042. */
  2043. public function updateline($id, $desc, $pu, $vatrate, $txlocaltax1 = 0, $txlocaltax2 = 0, $qty = 1, $idproduct = 0, $price_base_type = 'HT', $info_bits = 0, $type = 0, $remise_percent = 0, $notrigger = false, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_devise = 0, $ref_supplier = '', $rang = 0)
  2044. {
  2045. global $mysoc, $langs;
  2046. dol_syslog(get_class($this)."::updateline $id,$desc,$pu,$vatrate,$qty,$idproduct,$price_base_type,$info_bits,$type,$remise_percent,$notrigger,$date_start,$date_end,$fk_unit,$pu_devise,$ref_supplier", LOG_DEBUG);
  2047. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2048. $pu = price2num($pu);
  2049. $qty = price2num($qty);
  2050. $remise_percent = price2num($remise_percent);
  2051. $pu_devise = price2num($pu_devise);
  2052. // Check parameters
  2053. //if (! is_numeric($pu) || ! is_numeric($qty)) return -1;
  2054. if ($type < 0) {
  2055. return -1;
  2056. }
  2057. if ($date_start && $date_end && $date_start > $date_end) {
  2058. $langs->load("errors");
  2059. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  2060. return -1;
  2061. }
  2062. // Clean parameters
  2063. if (empty($vatrate)) {
  2064. $vatrate = 0;
  2065. }
  2066. if (empty($txlocaltax1)) {
  2067. $txlocaltax1 = 0;
  2068. }
  2069. if (empty($txlocaltax2)) {
  2070. $txlocaltax2 = 0;
  2071. }
  2072. $txlocaltax1 = price2num($txlocaltax1);
  2073. $txlocaltax2 = price2num($txlocaltax2);
  2074. // Calcul du total TTC et de la TVA pour la ligne a partir de
  2075. // qty, pu, remise_percent et txtva
  2076. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  2077. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  2078. $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty);
  2079. $reg = array();
  2080. // Clean vat code
  2081. $vat_src_code = '';
  2082. if (preg_match('/\((.*)\)/', $vatrate, $reg)) {
  2083. $vat_src_code = $reg[1];
  2084. $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
  2085. }
  2086. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_devise);
  2087. $total_ht = $tabprice[0];
  2088. $total_tva = $tabprice[1];
  2089. $total_ttc = $tabprice[2];
  2090. $pu_ht = $tabprice[3];
  2091. $pu_tva = $tabprice[4];
  2092. $pu_ttc = $tabprice[5];
  2093. $total_localtax1 = $tabprice[9];
  2094. $total_localtax2 = $tabprice[10];
  2095. // MultiCurrency
  2096. $multicurrency_total_ht = $tabprice[16];
  2097. $multicurrency_total_tva = $tabprice[17];
  2098. $multicurrency_total_ttc = $tabprice[18];
  2099. $pu_ht_devise = $tabprice[19];
  2100. if (empty($info_bits)) {
  2101. $info_bits = 0;
  2102. }
  2103. //Fetch current line from the database and then clone the object and set it in $oldline property
  2104. $line = new SupplierInvoiceLine($this->db);
  2105. $line->fetch($id);
  2106. $line->fetch_optionals();
  2107. $staticline = clone $line;
  2108. if ($idproduct) {
  2109. $product = new Product($this->db);
  2110. $result = $product->fetch($idproduct);
  2111. $product_type = $product->type;
  2112. } else {
  2113. $idproduct = $staticline->fk_product;
  2114. $product_type = $type;
  2115. }
  2116. $line->oldline = $staticline;
  2117. $line->context = $this->context;
  2118. $line->description = $desc;
  2119. $line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
  2120. $line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
  2121. $line->pu_ht = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
  2122. $line->pu_ttc = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ttc) : $pu_ttc); // For credit note, unit price always negative, always positive otherwise
  2123. $line->remise_percent = $remise_percent;
  2124. $line->ref_supplier = $ref_supplier;
  2125. $line->date_start = $date_start;
  2126. $line->date_end = $date_end;
  2127. $line->vat_src_code = $vat_src_code;
  2128. $line->tva_tx = $vatrate;
  2129. $line->localtax1_tx = $txlocaltax1;
  2130. $line->localtax2_tx = $txlocaltax2;
  2131. $line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  2132. $line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  2133. $line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht);
  2134. $line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
  2135. $line->total_localtax1 = $total_localtax1;
  2136. $line->total_localtax2 = $total_localtax2;
  2137. $line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
  2138. $line->fk_product = $idproduct;
  2139. $line->product_type = $product_type;
  2140. $line->info_bits = $info_bits;
  2141. $line->fk_unit = $fk_unit;
  2142. $line->rang = $rang;
  2143. if (is_array($array_options) && count($array_options) > 0) {
  2144. // We replace values in this->line->array_options only for entries defined into $array_options
  2145. foreach ($array_options as $key => $value) {
  2146. $line->array_options[$key] = $array_options[$key];
  2147. }
  2148. }
  2149. // Multicurrency
  2150. $line->multicurrency_subprice = $pu_ht_devise;
  2151. $line->multicurrency_total_ht = $multicurrency_total_ht;
  2152. $line->multicurrency_total_tva = $multicurrency_total_tva;
  2153. $line->multicurrency_total_ttc = $multicurrency_total_ttc;
  2154. $res = $line->update($notrigger);
  2155. if ($res < 1) {
  2156. $this->errors[] = $line->error;
  2157. } else {
  2158. // Update total price into invoice record
  2159. $res = $this->update_price('1', 'auto', 0, $this->thirdparty);
  2160. }
  2161. return $res;
  2162. }
  2163. /**
  2164. * Delete a detail line from database
  2165. *
  2166. * @param int $rowid Id of line to delete
  2167. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2168. * @return int <0 if KO, >0 if OK
  2169. */
  2170. public function deleteline($rowid, $notrigger = 0)
  2171. {
  2172. if (!$rowid) {
  2173. $rowid = $this->id;
  2174. }
  2175. $this->db->begin();
  2176. // Free the discount linked to a line of invoice
  2177. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  2178. $sql .= ' SET fk_invoice_supplier_line = NULL';
  2179. $sql .= ' WHERE fk_invoice_supplier_line = '.((int) $rowid);
  2180. dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
  2181. $result = $this->db->query($sql);
  2182. if (!$result) {
  2183. $this->error = $this->db->error();
  2184. $this->db->rollback();
  2185. return -2;
  2186. }
  2187. $line = new SupplierInvoiceLine($this->db);
  2188. if ($line->fetch($rowid) < 1) {
  2189. return -1;
  2190. }
  2191. $res = $line->delete($notrigger);
  2192. if ($res < 1) {
  2193. $this->errors[] = $line->error;
  2194. $this->db->rollback();
  2195. return -3;
  2196. } else {
  2197. $res = $this->update_price(1);
  2198. if ($res > 0) {
  2199. $this->db->commit();
  2200. return 1;
  2201. } else {
  2202. $this->db->rollback();
  2203. $this->error = $this->db->lasterror();
  2204. return -4;
  2205. }
  2206. }
  2207. }
  2208. /**
  2209. * Loads the info order information into the invoice object
  2210. *
  2211. * @param int $id Id of the invoice to load
  2212. * @return void
  2213. */
  2214. public function info($id)
  2215. {
  2216. $sql = 'SELECT c.rowid, datec, tms as datem, ';
  2217. $sql .= ' fk_user_author, fk_user_modif, fk_user_valid';
  2218. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as c';
  2219. $sql .= ' WHERE c.rowid = '.((int) $id);
  2220. $result = $this->db->query($sql);
  2221. if ($result) {
  2222. if ($this->db->num_rows($result)) {
  2223. $obj = $this->db->fetch_object($result);
  2224. $this->id = $obj->rowid;
  2225. if ($obj->fk_user_author) {
  2226. $cuser = new User($this->db);
  2227. $cuser->fetch($obj->fk_user_author);
  2228. $this->user_creation = $cuser;
  2229. }
  2230. if ($obj->fk_user_valid) {
  2231. $vuser = new User($this->db);
  2232. $vuser->fetch($obj->fk_user_valid);
  2233. $this->user_validation = $vuser;
  2234. }
  2235. if ($obj->fk_user_modif) {
  2236. $muser = new User($this->db);
  2237. $muser->fetch($obj->fk_user_modif);
  2238. $this->user_modification = $muser;
  2239. }
  2240. $this->date_creation = $this->db->jdate($obj->datec);
  2241. $this->date_modification = $this->db->jdate($obj->datem);
  2242. //$this->date_validation = $obj->datev; // This field is not available. Should be store into log table and using this function should be replaced with showing content of log (like for supplier orders)
  2243. }
  2244. $this->db->free($result);
  2245. } else {
  2246. dol_print_error($this->db);
  2247. }
  2248. }
  2249. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2250. /**
  2251. * Return list of replaceable invoices
  2252. * Status valid or abandoned for other reason + not paid + no payment + not already replaced
  2253. *
  2254. * @param int $socid Thirdparty id
  2255. * @return array|int Table of invoices ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1)
  2256. * <0 if error
  2257. */
  2258. public function list_replacable_supplier_invoices($socid = 0)
  2259. {
  2260. // phpcs:enable
  2261. global $conf;
  2262. $return = array();
  2263. $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut,";
  2264. $sql .= " ff.rowid as rowidnext";
  2265. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
  2266. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn";
  2267. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as ff ON f.rowid = ff.fk_facture_source";
  2268. $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
  2269. $sql .= " AND f.entity = ".$conf->entity;
  2270. $sql .= " AND f.paye = 0"; // Pas classee payee completement
  2271. $sql .= " AND pf.fk_paiementfourn IS NULL"; // Aucun paiement deja fait
  2272. $sql .= " AND ff.fk_statut IS NULL"; // Renvoi vrai si pas facture de remplacement
  2273. if ($socid > 0) {
  2274. $sql .= " AND f.fk_soc = ".((int) $socid);
  2275. }
  2276. $sql .= " ORDER BY f.ref";
  2277. dol_syslog(get_class($this)."::list_replacable_supplier_invoices", LOG_DEBUG);
  2278. $resql = $this->db->query($sql);
  2279. if ($resql) {
  2280. while ($obj = $this->db->fetch_object($resql)) {
  2281. $return[$obj->rowid] = array(
  2282. 'id' => $obj->rowid,
  2283. 'ref' => $obj->ref,
  2284. 'status' => $obj->fk_statut
  2285. );
  2286. }
  2287. //print_r($return);
  2288. return $return;
  2289. } else {
  2290. $this->error = $this->db->error();
  2291. return -1;
  2292. }
  2293. }
  2294. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2295. /**
  2296. * Return list of qualifying invoices for correction by credit note
  2297. * Invoices that respect the following rules are returned:
  2298. * (validated + payment in progress) or classified (paid in full or paid in part) + not already replaced + not already having
  2299. *
  2300. * @param int $socid Thirdparty id
  2301. * @return array|int Table of invoices ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>)
  2302. * <0 if error
  2303. */
  2304. public function list_qualified_avoir_supplier_invoices($socid = 0)
  2305. {
  2306. // phpcs:enable
  2307. global $conf;
  2308. $return = array();
  2309. $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiementfourn";
  2310. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
  2311. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn";
  2312. $sql .= " WHERE f.entity = ".$conf->entity;
  2313. $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
  2314. $sql .= " AND NOT EXISTS (SELECT rowid from ".MAIN_DB_PREFIX."facture_fourn as ff WHERE f.rowid = ff.fk_facture_source";
  2315. $sql .= " AND ff.type=".self::TYPE_REPLACEMENT.")";
  2316. $sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir
  2317. if ($socid > 0) {
  2318. $sql .= " AND f.fk_soc = ".((int) $socid);
  2319. }
  2320. $sql .= " ORDER BY f.ref";
  2321. dol_syslog(get_class($this)."::list_qualified_avoir_supplier_invoices", LOG_DEBUG);
  2322. $resql = $this->db->query($sql);
  2323. if ($resql) {
  2324. while ($obj = $this->db->fetch_object($resql)) {
  2325. $qualified = 0;
  2326. if ($obj->fk_statut == self::STATUS_VALIDATED) {
  2327. $qualified = 1;
  2328. }
  2329. if ($obj->fk_statut == self::STATUS_CLOSED) {
  2330. $qualified = 1;
  2331. }
  2332. if ($qualified) {
  2333. $paymentornot = ($obj->fk_paiementfourn ? 1 : 0);
  2334. $return[$obj->rowid] = array('ref'=>$obj->ref, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot);
  2335. }
  2336. }
  2337. return $return;
  2338. } else {
  2339. $this->error = $this->db->error();
  2340. return -1;
  2341. }
  2342. }
  2343. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2344. /**
  2345. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  2346. *
  2347. * @param User $user Object user
  2348. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  2349. */
  2350. public function load_board($user)
  2351. {
  2352. // phpcs:enable
  2353. global $conf, $langs;
  2354. $sql = 'SELECT ff.rowid, ff.date_lim_reglement as datefin, ff.fk_statut as status, ff.total_ht, ff.total_ttc';
  2355. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff';
  2356. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  2357. $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ff.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2358. }
  2359. $sql .= ' WHERE ff.paye = 0';
  2360. $sql .= ' AND ff.fk_statut > 0';
  2361. $sql .= " AND ff.entity = ".$conf->entity;
  2362. if ($user->socid) {
  2363. $sql .= ' AND ff.fk_soc = '.((int) $user->socid);
  2364. }
  2365. $resql = $this->db->query($sql);
  2366. if ($resql) {
  2367. $langs->load("bills");
  2368. $now = dol_now();
  2369. $response = new WorkboardResponse();
  2370. $response->warning_delay = $conf->facture->fournisseur->warning_delay / 60 / 60 / 24;
  2371. $response->label = $langs->trans("SupplierBillsToPay");
  2372. $response->labelShort = $langs->trans("StatusToPay");
  2373. $response->url = DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=billing&leftmenu=suppliers_bills';
  2374. $response->img = img_object($langs->trans("Bills"), "bill");
  2375. $facturestatic = new FactureFournisseur($this->db);
  2376. while ($obj = $this->db->fetch_object($resql)) {
  2377. $facturestatic->date_echeance = $this->db->jdate($obj->datefin);
  2378. $facturestatic->statut = $obj->status; // For backward compatibility
  2379. $facturestatic->status = $obj->status;
  2380. $response->nbtodo++;
  2381. $response->total += $obj->total_ht;
  2382. if ($facturestatic->hasDelay()) {
  2383. $response->nbtodolate++;
  2384. $response->url_late = DOL_URL_ROOT.'/fourn/facture/list.php?search_option=late&mainmenu=billing&leftmenu=suppliers_bills';
  2385. }
  2386. }
  2387. $this->db->free($resql);
  2388. return $response;
  2389. } else {
  2390. dol_print_error($this->db);
  2391. $this->error = $this->db->error();
  2392. return -1;
  2393. }
  2394. }
  2395. /**
  2396. * getTooltipContentArray
  2397. *
  2398. * @param array $params ex option, infologin
  2399. * @since v18
  2400. * @return array
  2401. */
  2402. public function getTooltipContentArray($params)
  2403. {
  2404. global $conf, $langs;
  2405. $langs->load('bills');
  2406. $datas = [];
  2407. $moretitle = $params['moretitle'] ?? '';
  2408. $picto = $this->picto;
  2409. if ($this->type == self::TYPE_REPLACEMENT) {
  2410. $picto .= 'r'; // Replacement invoice
  2411. }
  2412. if ($this->type == self::TYPE_CREDIT_NOTE) {
  2413. $picto .= 'a'; // Credit note
  2414. }
  2415. if ($this->type == self::TYPE_DEPOSIT) {
  2416. $picto .= 'd'; // Deposit invoice
  2417. }
  2418. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("SupplierInvoice").'</u>';
  2419. if ($this->type == self::TYPE_REPLACEMENT) {
  2420. $datas['picto'] .= '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceReplace").'</u>';
  2421. } elseif ($this->type == self::TYPE_CREDIT_NOTE) {
  2422. $datas['picto'] .= '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>';
  2423. } elseif ($this->type == self::TYPE_DEPOSIT) {
  2424. $datas['picto'] .= '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>';
  2425. }
  2426. if (isset($this->status)) {
  2427. $alreadypaid = -1;
  2428. if (isset($this->alreadypaid)) {
  2429. $alreadypaid = $this->alreadypaid;
  2430. }
  2431. $datas['picto'] .= ' '.$this->getLibStatut(5, $alreadypaid);
  2432. }
  2433. if ($moretitle) {
  2434. $datas['picto'] .= ' - '.$moretitle;
  2435. }
  2436. if (!empty($this->ref)) {
  2437. $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  2438. }
  2439. if (!empty($this->ref_supplier)) {
  2440. $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
  2441. }
  2442. if (!empty($this->label)) {
  2443. $datas['label'] = '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
  2444. }
  2445. if (!empty($this->date)) {
  2446. $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
  2447. }
  2448. if (!empty($this->date_echeance)) {
  2449. $datas['date_echeance'] = '<br><b>'.$langs->trans('DateDue').':</b> '.dol_print_date($this->date_echeance, 'day');
  2450. }
  2451. if (!empty($this->total_ht)) {
  2452. $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  2453. }
  2454. if (!empty($this->total_tva)) {
  2455. $datas['totaltva'] = '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  2456. }
  2457. if (!empty($this->total_ttc)) {
  2458. $datas['totalttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  2459. }
  2460. return $datas;
  2461. }
  2462. /**
  2463. * Return clicable name (with picto eventually)
  2464. *
  2465. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  2466. * @param string $option Where point the link
  2467. * @param int $max Max length of shown ref
  2468. * @param int $short 1=Return just URL
  2469. * @param string $moretitle Add more text to title tooltip
  2470. * @param int $notooltip 1=Disable tooltip
  2471. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  2472. * @param int $addlinktonotes Add link to show notes
  2473. * @return string String with URL
  2474. */
  2475. public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
  2476. {
  2477. global $langs, $conf, $user, $hookmanager;
  2478. $result = '';
  2479. if ($option == 'withdraw') {
  2480. $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id.'&type=bank-transfer';
  2481. } elseif ($option == 'document') {
  2482. $url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id;
  2483. } else {
  2484. $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id;
  2485. }
  2486. if ($short) {
  2487. return $url;
  2488. }
  2489. if ($option !== 'nolink') {
  2490. // Add param to save lastsearch_values or not
  2491. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  2492. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  2493. $add_save_lastsearch_values = 1;
  2494. }
  2495. if ($add_save_lastsearch_values) {
  2496. $url .= '&save_lastsearch_values=1';
  2497. }
  2498. }
  2499. $picto = $this->picto;
  2500. if ($this->type == self::TYPE_REPLACEMENT) {
  2501. $picto .= 'r'; // Replacement invoice
  2502. }
  2503. if ($this->type == self::TYPE_CREDIT_NOTE) {
  2504. $picto .= 'a'; // Credit note
  2505. }
  2506. if ($this->type == self::TYPE_DEPOSIT) {
  2507. $picto .= 'd'; // Deposit invoice
  2508. }
  2509. $params = [
  2510. 'id' => $this->id,
  2511. 'objecttype' => $this->element,
  2512. 'option' => $option,
  2513. 'moretitle' => $moretitle,
  2514. ];
  2515. $classfortooltip = 'classfortooltip';
  2516. $dataparams = '';
  2517. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  2518. $classfortooltip = 'classforajaxtooltip';
  2519. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  2520. $label = '';
  2521. } else {
  2522. $label = implode($this->getTooltipContentArray($params));
  2523. }
  2524. $ref = $this->ref;
  2525. if (empty($ref)) {
  2526. $ref = $this->id;
  2527. }
  2528. $linkclose = '';
  2529. if (empty($notooltip)) {
  2530. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  2531. $label = $langs->trans("ShowSupplierInvoice");
  2532. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  2533. }
  2534. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  2535. $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
  2536. }
  2537. $linkstart = '<a href="'.$url.'"';
  2538. $linkstart .= $linkclose.'>';
  2539. $linkend = '</a>';
  2540. $result .= $linkstart;
  2541. if ($withpicto) {
  2542. $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : $dataparams.' class="'.(($withpicto != 2) ? 'paddingright ' : '').$classfortooltip.'"'), 0, 0, $notooltip ? 0 : 1);
  2543. }
  2544. if ($withpicto != 2) {
  2545. $result .= ($max ?dol_trunc($ref, $max) : $ref);
  2546. }
  2547. $result .= $linkend;
  2548. if ($addlinktonotes) {
  2549. $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
  2550. if ($txttoshow) {
  2551. $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
  2552. $result .= ' <span class="note inline-block">';
  2553. $result .= '<a href="'.DOL_URL_ROOT.'/fourn/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
  2554. $result .= img_picto('', 'note');
  2555. $result .= '</a>';
  2556. $result .= '</span>';
  2557. }
  2558. }
  2559. global $action;
  2560. $hookmanager->initHooks(array($this->element . 'dao'));
  2561. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  2562. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2563. if ($reshook > 0) {
  2564. $result = $hookmanager->resPrint;
  2565. } else {
  2566. $result .= $hookmanager->resPrint;
  2567. }
  2568. return $result;
  2569. }
  2570. /**
  2571. * Return next reference of supplier invoice not already used (or last reference)
  2572. * according to numbering module defined into constant INVOICE_SUPPLIER_ADDON_NUMBER
  2573. *
  2574. * @param Societe $soc Thirdparty object
  2575. * @param string $mode 'next' for next value or 'last' for last value
  2576. * @return string free ref or last ref
  2577. */
  2578. public function getNextNumRef($soc, $mode = 'next')
  2579. {
  2580. global $db, $langs, $conf;
  2581. $langs->load("orders");
  2582. // Clean parameters (if not defined or using deprecated value)
  2583. if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) {
  2584. $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER = 'mod_facture_fournisseur_cactus';
  2585. }
  2586. $mybool = false;
  2587. $file = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER.".php";
  2588. $classname = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER;
  2589. // Include file with class
  2590. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2591. foreach ($dirmodels as $reldir) {
  2592. $dir = dol_buildpath($reldir."core/modules/supplier_invoice/");
  2593. // Load file with numbering class (if found)
  2594. $mybool |= @include_once $dir.$file;
  2595. }
  2596. if ($mybool === false) {
  2597. dol_print_error('', "Failed to include file ".$file);
  2598. return '';
  2599. }
  2600. $obj = new $classname();
  2601. $numref = "";
  2602. $numref = $obj->getNumRef($soc, $this, $mode);
  2603. if ($numref != "") {
  2604. return $numref;
  2605. } else {
  2606. $this->error = $obj->error;
  2607. return -1;
  2608. }
  2609. }
  2610. /**
  2611. * Initialise an instance with random values.
  2612. * Used to build previews or test instances.
  2613. * id must be 0 if object instance is a specimen.
  2614. *
  2615. * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines
  2616. * @return void
  2617. */
  2618. public function initAsSpecimen($option = '')
  2619. {
  2620. global $langs, $conf;
  2621. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  2622. $now = dol_now();
  2623. // Load array of products prodids
  2624. $num_prods = 0;
  2625. $prodids = array();
  2626. $sql = "SELECT rowid";
  2627. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  2628. $sql .= " WHERE entity IN (".getEntity('product').")";
  2629. $sql .= $this->db->plimit(100);
  2630. $resql = $this->db->query($sql);
  2631. if ($resql) {
  2632. $num_prods = $this->db->num_rows($resql);
  2633. $i = 0;
  2634. while ($i < $num_prods) {
  2635. $i++;
  2636. $row = $this->db->fetch_row($resql);
  2637. $prodids[$i] = $row[0];
  2638. }
  2639. }
  2640. // Initialise parametres
  2641. $this->id = 0;
  2642. $this->ref = 'SPECIMEN';
  2643. $this->ref_supplier = 'SUPPLIER_REF_SPECIMEN';
  2644. $this->specimen = 1;
  2645. $this->socid = 1;
  2646. $this->date = $now;
  2647. $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
  2648. $this->cond_reglement_code = 'RECEP';
  2649. $this->mode_reglement_code = 'CHQ';
  2650. $this->note_public = 'This is a comment (public)';
  2651. $this->note_private = 'This is a comment (private)';
  2652. $this->multicurrency_tx = 1;
  2653. $this->multicurrency_code = $conf->currency;
  2654. $xnbp = 0;
  2655. if (empty($option) || $option != 'nolines') {
  2656. // Lines
  2657. $nbp = 5;
  2658. while ($xnbp < $nbp) {
  2659. $line = new SupplierInvoiceLine($this->db);
  2660. $line->desc = $langs->trans("Description")." ".$xnbp;
  2661. $line->qty = 1;
  2662. $line->subprice = 100;
  2663. $line->pu_ht = 100; // the canelle template use pu_ht and not subprice
  2664. $line->price = 100;
  2665. $line->tva_tx = 19.6;
  2666. $line->localtax1_tx = 0;
  2667. $line->localtax2_tx = 0;
  2668. if ($xnbp == 2) {
  2669. $line->total_ht = 50;
  2670. $line->total_ttc = 59.8;
  2671. $line->total_tva = 9.8;
  2672. $line->remise_percent = 50;
  2673. } else {
  2674. $line->total_ht = 100;
  2675. $line->total_ttc = 119.6;
  2676. $line->total_tva = 19.6;
  2677. $line->remise_percent = 0;
  2678. }
  2679. if ($num_prods > 0) {
  2680. $prodid = mt_rand(1, $num_prods);
  2681. $line->fk_product = $prodids[$prodid];
  2682. }
  2683. $line->product_type = 0;
  2684. $this->lines[$xnbp] = $line;
  2685. $this->total_ht += $line->total_ht;
  2686. $this->total_tva += $line->total_tva;
  2687. $this->total_ttc += $line->total_ttc;
  2688. $xnbp++;
  2689. }
  2690. }
  2691. $this->amount_ht = $xnbp * 100;
  2692. $this->total_ht = $xnbp * 100;
  2693. $this->total_tva = $xnbp * 19.6;
  2694. $this->total_ttc = $xnbp * 119.6;
  2695. }
  2696. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2697. /**
  2698. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  2699. *
  2700. * @return int <0 if KO, >0 if OK
  2701. */
  2702. public function load_state_board()
  2703. {
  2704. // phpcs:enable
  2705. global $conf, $user;
  2706. $this->nb = array();
  2707. $clause = "WHERE";
  2708. $sql = "SELECT count(f.rowid) as nb";
  2709. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
  2710. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
  2711. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  2712. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  2713. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  2714. $clause = "AND";
  2715. }
  2716. $sql .= " ".$clause." f.entity = ".$conf->entity;
  2717. $resql = $this->db->query($sql);
  2718. if ($resql) {
  2719. while ($obj = $this->db->fetch_object($resql)) {
  2720. $this->nb["supplier_invoices"] = $obj->nb;
  2721. }
  2722. $this->db->free($resql);
  2723. return 1;
  2724. } else {
  2725. dol_print_error($this->db);
  2726. $this->error = $this->db->error();
  2727. return -1;
  2728. }
  2729. }
  2730. /**
  2731. * Load an object from its id and create a new one in database
  2732. *
  2733. * @param User $user User that clone
  2734. * @param int $fromid Id of object to clone
  2735. * @param int $invertdetail Reverse sign of amounts for lines
  2736. * @return int New id of clone
  2737. */
  2738. public function createFromClone(User $user, $fromid, $invertdetail = 0)
  2739. {
  2740. global $conf, $langs;
  2741. $error = 0;
  2742. $object = new FactureFournisseur($this->db);
  2743. $this->db->begin();
  2744. // Load source object
  2745. $object->fetch($fromid);
  2746. $object->id = 0;
  2747. $object->statut = self::STATUS_DRAFT; // For backward compatibility
  2748. $object->status = self::STATUS_DRAFT;
  2749. $object->fetch_thirdparty(); // We need it to recalculate VAT localtaxes according to main sale taxes and vendor
  2750. // Clear fields
  2751. $object->ref_supplier = (empty($this->ref_supplier) ? $langs->trans("CopyOf").' '.$object->ref_supplier : $this->ref_supplier);
  2752. $object->author = $user->id;
  2753. $object->user_valid = 0;
  2754. $object->fk_facture_source = 0;
  2755. $object->date_creation = '';
  2756. $object->date_validation = '';
  2757. $object->date = (empty($this->date) ? dol_now() : $this->date);
  2758. $object->ref_client = '';
  2759. $object->close_code = '';
  2760. $object->close_note = '';
  2761. if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
  2762. $object->note_private = '';
  2763. $object->note_public = '';
  2764. }
  2765. $object->date_echeance = $object->calculate_date_lim_reglement();
  2766. // Loop on each line of new invoice
  2767. foreach ($object->lines as $i => $line) {
  2768. if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
  2769. unset($object->lines[$i]);
  2770. }
  2771. }
  2772. // Create clone
  2773. $object->context['createfromclone'] = 'createfromclone';
  2774. $result = $object->create($user);
  2775. // Other options
  2776. if ($result < 0) {
  2777. $this->error = $object->error;
  2778. $this->errors = $object->errors;
  2779. $error++;
  2780. }
  2781. if (!$error) {
  2782. }
  2783. unset($object->context['createfromclone']);
  2784. // End
  2785. if (!$error) {
  2786. $this->db->commit();
  2787. return $object->id;
  2788. } else {
  2789. $this->db->rollback();
  2790. return -1;
  2791. }
  2792. }
  2793. /**
  2794. * Create a document onto disk according to template model.
  2795. *
  2796. * @param string $modele Force template to use ('' to not force)
  2797. * @param Translate $outputlangs Object lang a utiliser pour traduction
  2798. * @param int $hidedetails Hide details of lines
  2799. * @param int $hidedesc Hide description
  2800. * @param int $hideref Hide ref
  2801. * @param null|array $moreparams Array to provide more information
  2802. * @return int <0 if KO, 0 if nothing done, >0 if OK
  2803. */
  2804. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  2805. {
  2806. global $conf, $user, $langs;
  2807. $langs->load("suppliers");
  2808. $outputlangs->load("products");
  2809. // Set the model on the model name to use
  2810. if (empty($modele)) {
  2811. if (!empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) {
  2812. $modele = $conf->global->INVOICE_SUPPLIER_ADDON_PDF;
  2813. } else {
  2814. $modele = ''; // No default value. For supplier invoice, we allow to disable all PDF generation
  2815. }
  2816. }
  2817. if (empty($modele)) {
  2818. return 0;
  2819. } else {
  2820. $modelpath = "core/modules/supplier_invoice/doc/";
  2821. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  2822. }
  2823. }
  2824. /**
  2825. * Returns the rights used for this class
  2826. * @return stdClass
  2827. */
  2828. public function getRights()
  2829. {
  2830. global $user;
  2831. return $user->rights->fournisseur->facture;
  2832. }
  2833. /**
  2834. * Function used to replace a thirdparty id with another one.
  2835. *
  2836. * @param DoliDB $dbs Database handler, because function is static we name it $dbs not $db to avoid breaking coding test
  2837. * @param int $origin_id Old thirdparty id
  2838. * @param int $dest_id New thirdparty id
  2839. * @return bool
  2840. */
  2841. public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
  2842. {
  2843. $tables = array(
  2844. 'facture_fourn'
  2845. );
  2846. return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
  2847. }
  2848. /**
  2849. * Function used to replace a product id with another one.
  2850. *
  2851. * @param DoliDB $db Database handler
  2852. * @param int $origin_id Old product id
  2853. * @param int $dest_id New product id
  2854. * @return bool
  2855. */
  2856. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  2857. {
  2858. $tables = array(
  2859. 'facture_fourn_det'
  2860. );
  2861. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  2862. }
  2863. /**
  2864. * Is the payment of the supplier invoice having a delay?
  2865. *
  2866. * @return bool
  2867. */
  2868. public function hasDelay()
  2869. {
  2870. global $conf;
  2871. $now = dol_now();
  2872. if (!$this->date_echeance) {
  2873. return false;
  2874. }
  2875. $status = isset($this->status) ? $this->status : $this->statut;
  2876. return ($status == self::STATUS_VALIDATED) && ($this->date_echeance < ($now - $conf->facture->fournisseur->warning_delay));
  2877. }
  2878. /**
  2879. * Is credit note used
  2880. *
  2881. * @return bool
  2882. */
  2883. public function isCreditNoteUsed()
  2884. {
  2885. $isUsed = false;
  2886. $sql = "SELECT fk_invoice_supplier FROM ".MAIN_DB_PREFIX."societe_remise_except WHERE fk_invoice_supplier_source = ".((int) $this->id);
  2887. $resql = $this->db->query($sql);
  2888. if (!empty($resql)) {
  2889. $obj = $this->db->fetch_object($resql);
  2890. if (!empty($obj->fk_invoice_supplier)) {
  2891. $isUsed = true;
  2892. }
  2893. }
  2894. return $isUsed;
  2895. }
  2896. /**
  2897. * Return clicable link of object (with eventually picto)
  2898. *
  2899. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  2900. * @param array $arraydata Array of data
  2901. * @return string HTML Code for Kanban thumb.
  2902. */
  2903. public function getKanbanView($option = '', $arraydata = null)
  2904. {
  2905. global $langs;
  2906. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  2907. $return = '<div class="box-flex-item box-flex-grow-zero">';
  2908. $return .= '<div class="info-box info-box-sm">';
  2909. $return .= '<span class="info-box-icon bg-infobox-action">';
  2910. $return .= img_picto('', $this->picto);
  2911. $return .= '</span>';
  2912. $return .= '<div class="info-box-content">';
  2913. $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
  2914. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  2915. if (!empty($arraydata['thirdparty'])) {
  2916. $return .= '<br><span class="info-box-label">'.$arraydata['thirdparty'].'</span>';
  2917. }
  2918. if (property_exists($this, 'date')) {
  2919. $return .= '<br><span class="info-box-label">'.dol_print_date($this->date, 'day').'</span>';
  2920. }
  2921. if (property_exists($this, 'total_ht')) {
  2922. $return .= ' &nbsp; <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans("AmountHT")).'">'.price($this->total_ht);
  2923. $return .= ' '.$langs->trans("HT");
  2924. $return .= '</span>';
  2925. }
  2926. if (method_exists($this, 'getLibStatut')) {
  2927. $alreadypaid = (empty($arraydata['alreadypaid']) ? 0 : $arraydata['alreadypaid']);
  2928. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3, $alreadypaid).'</div>';
  2929. }
  2930. $return .= '</div>';
  2931. $return .= '</div>';
  2932. $return .= '</div>';
  2933. return $return;
  2934. }
  2935. /**
  2936. * Change the option VAT reverse charge
  2937. *
  2938. * @param int $vatreversecharge 0 = Off, 1 = On
  2939. * @return int 1 if OK, 0 if KO
  2940. */
  2941. public function setVATReverseCharge($vatreversecharge)
  2942. {
  2943. if (!$this->table_element) {
  2944. dol_syslog(get_class($this)."::setVATReverseCharge was called on objet with property table_element not defined", LOG_ERR);
  2945. return -1;
  2946. }
  2947. dol_syslog(get_class($this).'::setVATReverseCharge('.$vatreversecharge.')');
  2948. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2949. $sql .= " SET vat_reverse_charge = ".((int) $vatreversecharge);
  2950. $sql .= " WHERE rowid=".((int) $this->id);
  2951. if ($this->db->query($sql)) {
  2952. $this->vat_reverse_charge = ($vatreversecharge == 0) ? 0 : 1;
  2953. return 1;
  2954. } else {
  2955. dol_syslog(get_class($this).'::setVATReverseCharge Error ', LOG_DEBUG);
  2956. $this->error = $this->db->error();
  2957. return 0;
  2958. }
  2959. }
  2960. }
  2961. /**
  2962. * Class to manage line invoices
  2963. */
  2964. class SupplierInvoiceLine extends CommonObjectLine
  2965. {
  2966. /**
  2967. * @var string ID to identify managed object
  2968. */
  2969. public $element = 'facture_fourn_det';
  2970. /**
  2971. * @var string Name of table without prefix where object is stored
  2972. */
  2973. public $table_element = 'facture_fourn_det';
  2974. public $oldline;
  2975. /**
  2976. * @deprecated
  2977. * @see $product_ref
  2978. */
  2979. public $ref;
  2980. /**
  2981. * Internal ref
  2982. * @var string
  2983. */
  2984. public $product_ref;
  2985. /**
  2986. * Supplier reference of price when we added the line. May have been changed after line was added.
  2987. * TODO Rename field ref to ref_supplier into table llx_facture_fourn_det and llx_commande_fournisseurdet and update fields into updateline
  2988. * @var string
  2989. */
  2990. public $ref_supplier;
  2991. /**
  2992. * Product description
  2993. * @var string
  2994. */
  2995. public $product_desc;
  2996. /**
  2997. * Unit price before taxes
  2998. * @var float
  2999. * @deprecated Use $subprice
  3000. * @see $subprice
  3001. */
  3002. public $pu_ht;
  3003. /**
  3004. * Unit price excluded taxes
  3005. * @var float
  3006. */
  3007. public $subprice;
  3008. /**
  3009. * Unit price included taxes
  3010. * @var float
  3011. */
  3012. public $pu_ttc;
  3013. /**
  3014. * Id of the corresponding supplier invoice
  3015. * @var int
  3016. */
  3017. public $fk_facture_fourn;
  3018. /**
  3019. * This field may contains label of line (when invoice create from order)
  3020. * @var string
  3021. * @deprecated
  3022. */
  3023. public $label;
  3024. /**
  3025. * Description of the line
  3026. * @var string
  3027. */
  3028. public $description;
  3029. public $date_start;
  3030. public $date_end;
  3031. public $skip_update_total; // Skip update price total for special lines
  3032. /**
  3033. * @var int Situation advance percentage
  3034. */
  3035. public $situation_percent;
  3036. /**
  3037. * @var int Previous situation line id reference
  3038. */
  3039. public $fk_prev_id;
  3040. /**
  3041. * VAT code
  3042. * @var string
  3043. */
  3044. public $vat_src_code;
  3045. /**
  3046. * VAT %
  3047. * @var float
  3048. */
  3049. public $tva_tx;
  3050. /**
  3051. * Local tax 1 %
  3052. * @var float
  3053. */
  3054. public $localtax1_tx;
  3055. /**
  3056. * Local tax 2 %
  3057. * @var float
  3058. */
  3059. public $localtax2_tx;
  3060. /**
  3061. * Quantity
  3062. * @var double
  3063. */
  3064. public $qty;
  3065. /**
  3066. * Percent of discount
  3067. * @var float
  3068. */
  3069. public $remise_percent;
  3070. /**
  3071. * Total amount without taxes
  3072. * @var float
  3073. */
  3074. public $total_ht;
  3075. /**
  3076. * Total amount with taxes
  3077. * @var float
  3078. */
  3079. public $total_ttc;
  3080. /**
  3081. * Total amount of taxes
  3082. * @var float
  3083. */
  3084. public $total_tva;
  3085. /**
  3086. * Total local tax 1 amount
  3087. * @var float
  3088. */
  3089. public $total_localtax1;
  3090. /**
  3091. * Total local tax 2 amount
  3092. * @var float
  3093. */
  3094. public $total_localtax2;
  3095. /**
  3096. * @var int ID
  3097. */
  3098. public $fk_product;
  3099. /**
  3100. * Type of the product. 0 for product 1 for service
  3101. * @var int
  3102. */
  3103. public $product_type;
  3104. /**
  3105. * Label of the product
  3106. * @var string
  3107. */
  3108. public $product_label;
  3109. /**
  3110. * List of cumulative options:
  3111. * Bit 0: 0 si TVA normal - 1 si TVA NPR
  3112. * Bit 1: 0 si ligne normal - 1 si bit discount (link to line into llx_remise_except)
  3113. * @var int
  3114. */
  3115. public $info_bits;
  3116. /**
  3117. * Link to line into llx_remise_except
  3118. * @var int
  3119. */
  3120. public $fk_remise_except;
  3121. /**
  3122. * @var int ID
  3123. */
  3124. public $fk_parent_line;
  3125. public $special_code;
  3126. /**
  3127. * @var int rank of line
  3128. */
  3129. public $rang;
  3130. /**
  3131. * Total local tax 1 amount
  3132. * @var float
  3133. */
  3134. public $localtax1_type;
  3135. /**
  3136. * Total local tax 2 amount
  3137. * @var float
  3138. */
  3139. public $localtax2_type;
  3140. // Multicurrency
  3141. /**
  3142. * @var int ID
  3143. */
  3144. public $fk_multicurrency;
  3145. public $multicurrency_code;
  3146. public $multicurrency_subprice;
  3147. public $multicurrency_total_ht;
  3148. public $multicurrency_total_tva;
  3149. public $multicurrency_total_ttc;
  3150. /**
  3151. * Constructor
  3152. *
  3153. * @param DoliDB $db Database handler
  3154. */
  3155. public function __construct($db)
  3156. {
  3157. $this->db = $db;
  3158. }
  3159. /**
  3160. * Retrieves a supplier invoice line
  3161. *
  3162. * @param int $rowid Line id
  3163. * @return int <0 KO; 0 NOT FOUND; 1 OK
  3164. */
  3165. public function fetch($rowid)
  3166. {
  3167. $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.date_start, f.date_end, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.tva_tx';
  3168. $sql .= ', f.localtax1_type, f.localtax2_type, f.localtax1_tx, f.localtax2_tx, f.total_localtax1, f.total_localtax2, f.fk_remise_except';
  3169. $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_facture_fourn, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
  3170. $sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc';
  3171. $sql .= ', f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, multicurrency_total_ttc';
  3172. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
  3173. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
  3174. $sql .= ' WHERE f.rowid = '.((int) $rowid);
  3175. $sql .= ' ORDER BY f.rang, f.rowid';
  3176. $query = $this->db->query($sql);
  3177. if (!$query) {
  3178. $this->errors[] = $this->db->error();
  3179. return -1;
  3180. }
  3181. if (!$this->db->num_rows($query)) {
  3182. return 0;
  3183. }
  3184. $obj = $this->db->fetch_object($query);
  3185. $this->id = $obj->rowid;
  3186. $this->rowid = $obj->rowid;
  3187. $this->fk_facture_fourn = $obj->fk_facture_fourn;
  3188. $this->description = $obj->description;
  3189. $this->date_start = $obj->date_start;
  3190. $this->date_end = $obj->date_end;
  3191. $this->product_ref = $obj->product_ref;
  3192. $this->ref_supplier = $obj->ref_supplier;
  3193. $this->product_desc = $obj->product_desc;
  3194. $this->subprice = $obj->pu_ht;
  3195. $this->pu_ht = $obj->pu_ht;
  3196. $this->pu_ttc = $obj->pu_ttc;
  3197. $this->tva_tx = $obj->tva_tx;
  3198. $this->localtax1_tx = $obj->localtax1_tx;
  3199. $this->localtax2_tx = $obj->localtax2_tx;
  3200. $this->localtax1_type = $obj->localtax1_type;
  3201. $this->localtax2_type = $obj->localtax2_type;
  3202. $this->qty = $obj->qty;
  3203. $this->remise_percent = $obj->remise_percent;
  3204. $this->fk_remise_except = $obj->fk_remise_except;
  3205. //$this->tva = $obj->total_tva; // deprecated
  3206. $this->total_ht = $obj->total_ht;
  3207. $this->total_tva = $obj->total_tva;
  3208. $this->total_localtax1 = $obj->total_localtax1;
  3209. $this->total_localtax2 = $obj->total_localtax2;
  3210. $this->total_ttc = $obj->total_ttc;
  3211. $this->fk_product = $obj->fk_product;
  3212. $this->product_type = $obj->product_type;
  3213. $this->product_label = $obj->product_label;
  3214. $this->info_bits = $obj->info_bits;
  3215. $this->tva_npr = ($obj->info_bits & 1 == 1) ? 1 : 0;
  3216. $this->fk_parent_line = $obj->fk_parent_line;
  3217. $this->special_code = $obj->special_code;
  3218. $this->rang = $obj->rang;
  3219. $this->fk_unit = $obj->fk_unit;
  3220. $this->multicurrency_subprice = $obj->multicurrency_subprice;
  3221. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  3222. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  3223. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  3224. $this->fetch_optionals();
  3225. return 1;
  3226. }
  3227. /**
  3228. * Deletes a line
  3229. *
  3230. * @param bool|int $notrigger 1=Does not execute triggers, 0= execute triggers
  3231. * @return int 0 if KO, 1 if OK
  3232. */
  3233. public function delete($notrigger = 0)
  3234. {
  3235. global $user, $conf;
  3236. dol_syslog(get_class($this)."::deleteline rowid=".((int) $this->id), LOG_DEBUG);
  3237. $error = 0;
  3238. $this->db->begin();
  3239. if (!$notrigger) {
  3240. if ($this->call_trigger('LINEBILL_SUPPLIER_DELETE', $user) < 0) {
  3241. $error++;
  3242. }
  3243. }
  3244. $this->deleteObjectLinked();
  3245. // Remove extrafields
  3246. if (!$error) {
  3247. $result = $this->deleteExtraFields();
  3248. if ($result < 0) {
  3249. $error++;
  3250. dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
  3251. }
  3252. }
  3253. if (!$error) {
  3254. // Supprime ligne
  3255. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det ';
  3256. $sql .= " WHERE rowid = ".((int) $this->id);
  3257. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  3258. $resql = $this->db->query($sql);
  3259. if (!$resql) {
  3260. $error++;
  3261. $this->error = $this->db->lasterror();
  3262. }
  3263. }
  3264. if (!$error) {
  3265. $this->db->commit();
  3266. return 1;
  3267. } else {
  3268. $this->db->rollback();
  3269. return -1;
  3270. }
  3271. }
  3272. /**
  3273. * Update a supplier invoice line
  3274. *
  3275. * @param int $notrigger Disable triggers
  3276. * @return int <0 if KO, >0 if OK
  3277. */
  3278. public function update($notrigger = 0)
  3279. {
  3280. global $conf;
  3281. $pu = price2num($this->pu_ht);
  3282. $qty = price2num($this->qty);
  3283. // Check parameters
  3284. if (empty($this->qty)) {
  3285. $this->qty = 0;
  3286. }
  3287. if ($this->product_type < 0) {
  3288. return -1;
  3289. }
  3290. // Clean parameters
  3291. if (empty($this->remise_percent)) {
  3292. $this->remise_percent = 0;
  3293. }
  3294. if (empty($this->tva_tx)) {
  3295. $this->tva_tx = 0;
  3296. }
  3297. if (empty($this->localtax1_tx)) {
  3298. $this->localtax1_tx = 0;
  3299. }
  3300. if (empty($this->localtax2_tx)) {
  3301. $this->localtax2_tx = 0;
  3302. }
  3303. if (empty($this->pa_ht)) {
  3304. $this->pa_ht = 0;
  3305. }
  3306. if (empty($this->multicurrency_subprice)) {
  3307. $this->multicurrency_subprice = 0;
  3308. }
  3309. if (empty($this->multicurrency_total_ht)) {
  3310. $this->multicurrency_total_ht = 0;
  3311. }
  3312. if (empty($this->multicurrency_total_tva)) {
  3313. $this->multicurrency_total_tva = 0;
  3314. }
  3315. if (empty($this->multicurrency_total_ttc)) {
  3316. $this->multicurrency_total_ttc = 0;
  3317. }
  3318. $fk_product = (int) $this->fk_product;
  3319. $fk_unit = (int) $this->fk_unit;
  3320. $this->db->begin();
  3321. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET";
  3322. $sql .= " description = '".$this->db->escape($this->description)."'";
  3323. $sql .= ", ref = '".$this->db->escape($this->ref_supplier ? $this->ref_supplier : $this->ref)."'";
  3324. $sql .= ", date_start = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null");
  3325. $sql .= ", date_end = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null");
  3326. $sql .= ", pu_ht = ".price2num($this->pu_ht);
  3327. $sql .= ", pu_ttc = ".price2num($this->pu_ttc);
  3328. $sql .= ", qty = ".price2num($this->qty);
  3329. $sql .= ", remise_percent = ".price2num($this->remise_percent);
  3330. if ($this->fk_remise_except > 0) $sql .= ", fk_remise_except=".((int) $this->fk_remise_except);
  3331. else $sql .= ", fk_remise_except=null";
  3332. $sql .= ", vat_src_code = '".$this->db->escape(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'";
  3333. $sql .= ", tva_tx = ".price2num($this->tva_tx);
  3334. $sql .= ", localtax1_tx = ".price2num($this->localtax1_tx);
  3335. $sql .= ", localtax2_tx = ".price2num($this->localtax2_tx);
  3336. $sql .= ", localtax1_type = '".$this->db->escape($this->localtax1_type)."'";
  3337. $sql .= ", localtax2_type = '".$this->db->escape($this->localtax2_type)."'";
  3338. $sql .= ", total_ht = ".price2num($this->total_ht);
  3339. $sql .= ", tva= ".price2num($this->total_tva);
  3340. $sql .= ", total_localtax1= ".price2num($this->total_localtax1);
  3341. $sql .= ", total_localtax2= ".price2num($this->total_localtax2);
  3342. $sql .= ", total_ttc = ".price2num($this->total_ttc);
  3343. $sql .= ", fk_product = ".($fk_product > 0 ? (int) $fk_product : 'null');
  3344. $sql .= ", product_type = ".((int) $this->product_type);
  3345. $sql .= ", info_bits = ".((int) $this->info_bits);
  3346. $sql .= ", fk_unit = ".($fk_unit > 0 ? (int) $fk_unit : 'null');
  3347. if (!empty($this->rang)) {
  3348. $sql .= ", rang=".((int) $this->rang);
  3349. }
  3350. // Multicurrency
  3351. $sql .= " , multicurrency_subprice=".price2num($this->multicurrency_subprice);
  3352. $sql .= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
  3353. $sql .= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
  3354. $sql .= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
  3355. $sql .= " WHERE rowid = ".((int) $this->id);
  3356. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  3357. $resql = $this->db->query($sql);
  3358. if (!$resql) {
  3359. $this->db->rollback();
  3360. $this->error = $this->db->lasterror();
  3361. return -1;
  3362. }
  3363. $this->rowid = $this->id;
  3364. $error = 0;
  3365. if (!$error) {
  3366. $result = $this->insertExtraFields();
  3367. if ($result < 0) {
  3368. $error++;
  3369. }
  3370. }
  3371. if (!$error && !$notrigger) {
  3372. global $langs, $user;
  3373. // Call trigger
  3374. if ($this->call_trigger('LINEBILL_SUPPLIER_MODIFY', $user) < 0) {
  3375. $this->db->rollback();
  3376. return -1;
  3377. }
  3378. // End call triggers
  3379. }
  3380. if ($error) {
  3381. $this->db->rollback();
  3382. return -1;
  3383. }
  3384. $this->db->commit();
  3385. return 1;
  3386. }
  3387. /**
  3388. * Insert line into database
  3389. *
  3390. * @param int $notrigger 1 no triggers
  3391. * @return int <0 if KO, >0 if OK
  3392. */
  3393. public function insert($notrigger = 0)
  3394. {
  3395. global $user, $conf, $langs;
  3396. $error = 0;
  3397. dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
  3398. // Clean parameters
  3399. $this->desc = trim($this->desc);
  3400. if (empty($this->tva_tx)) {
  3401. $this->tva_tx = 0;
  3402. }
  3403. if (empty($this->localtax1_tx)) {
  3404. $this->localtax1_tx = 0;
  3405. }
  3406. if (empty($this->localtax2_tx)) {
  3407. $this->localtax2_tx = 0;
  3408. }
  3409. if (empty($this->localtax1_type)) {
  3410. $this->localtax1_type = '0';
  3411. }
  3412. if (empty($this->localtax2_type)) {
  3413. $this->localtax2_type = '0';
  3414. }
  3415. if (empty($this->total_tva)) {
  3416. $this->total_tva = 0;
  3417. }
  3418. if (empty($this->total_localtax1)) {
  3419. $this->total_localtax1 = 0;
  3420. }
  3421. if (empty($this->total_localtax2)) {
  3422. $this->total_localtax2 = 0;
  3423. }
  3424. if (empty($this->rang)) {
  3425. $this->rang = 0;
  3426. }
  3427. if (empty($this->remise_percent)) {
  3428. $this->remise_percent = 0;
  3429. }
  3430. if (empty($this->info_bits)) {
  3431. $this->info_bits = 0;
  3432. }
  3433. if (empty($this->subprice)) {
  3434. $this->subprice = 0;
  3435. }
  3436. if (empty($this->special_code)) {
  3437. $this->special_code = 0;
  3438. }
  3439. if (empty($this->fk_parent_line)) {
  3440. $this->fk_parent_line = 0;
  3441. }
  3442. if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
  3443. $this->situation_percent = 100;
  3444. }
  3445. if (empty($this->pa_ht)) {
  3446. $this->pa_ht = 0;
  3447. }
  3448. if (empty($this->multicurrency_subprice)) {
  3449. $this->multicurrency_subprice = 0;
  3450. }
  3451. if (empty($this->multicurrency_total_ht)) {
  3452. $this->multicurrency_total_ht = 0;
  3453. }
  3454. if (empty($this->multicurrency_total_tva)) {
  3455. $this->multicurrency_total_tva = 0;
  3456. }
  3457. if (empty($this->multicurrency_total_ttc)) {
  3458. $this->multicurrency_total_ttc = 0;
  3459. }
  3460. // Check parameters
  3461. if ($this->product_type < 0) {
  3462. $this->error = 'ErrorProductTypeMustBe0orMore';
  3463. return -1;
  3464. }
  3465. if (!empty($this->fk_product) && $this->fk_product > 0) {
  3466. // Check product exists
  3467. $result = Product::isExistingObject('product', $this->fk_product);
  3468. if ($result <= 0) {
  3469. $this->error = 'ErrorProductIdDoesNotExists';
  3470. return -1;
  3471. }
  3472. }
  3473. $this->db->begin();
  3474. // Insertion dans base de la ligne
  3475. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
  3476. $sql .= ' (fk_facture_fourn, fk_parent_line, label, description, ref, qty,';
  3477. $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
  3478. $sql .= ' fk_product, product_type, remise_percent, fk_remise_except, pu_ht, pu_ttc,';
  3479. $sql .= ' date_start, date_end, fk_code_ventilation, rang, special_code,';
  3480. $sql .= ' info_bits, total_ht, tva, total_ttc, total_localtax1, total_localtax2, fk_unit';
  3481. $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3482. $sql .= ')';
  3483. $sql .= " VALUES (".$this->fk_facture_fourn.",";
  3484. $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").",";
  3485. $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
  3486. $sql .= " '".$this->db->escape($this->desc ? $this->desc : $this->description)."',";
  3487. $sql .= " '".$this->db->escape($this->ref_supplier)."',";
  3488. $sql .= " ".price2num($this->qty).",";
  3489. $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
  3490. $sql .= " ".price2num($this->tva_tx).",";
  3491. $sql .= " ".price2num($this->localtax1_tx).",";
  3492. $sql .= " ".price2num($this->localtax2_tx).",";
  3493. $sql .= " '".$this->db->escape($this->localtax1_type)."',";
  3494. $sql .= " '".$this->db->escape($this->localtax2_type)."',";
  3495. $sql .= ' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product : "null").',';
  3496. $sql .= " ".((int) $this->product_type).",";
  3497. $sql .= " ".price2num($this->remise_percent).",";
  3498. $sql .= ' '.(!empty($this->fk_remise_except) ? ((int) $this->fk_remise_except) : "null").',';
  3499. $sql .= " ".price2num($this->subprice).",";
  3500. $sql .= " ".(!empty($this->qty) ?price2num($this->total_ttc / $this->qty) : price2num($this->total_ttc)).",";
  3501. $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").",";
  3502. $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").",";
  3503. $sql .= ' '.(!empty($this->fk_code_ventilation) ? $this->fk_code_ventilation : 0).',';
  3504. $sql .= ' '.((int) $this->rang).',';
  3505. $sql .= ' '.((int) $this->special_code).',';
  3506. $sql .= " ".((int) $this->info_bits).",";
  3507. $sql .= " ".price2num($this->total_ht).",";
  3508. $sql .= " ".price2num($this->total_tva).",";
  3509. $sql .= " ".price2num($this->total_ttc).",";
  3510. $sql .= " ".price2num($this->total_localtax1).",";
  3511. $sql .= " ".price2num($this->total_localtax2);
  3512. $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
  3513. $sql .= ", ".(int) $this->fk_multicurrency;
  3514. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  3515. $sql .= ", ".price2num($this->multicurrency_subprice);
  3516. $sql .= ", ".price2num($this->multicurrency_total_ht);
  3517. $sql .= ", ".price2num($this->multicurrency_total_tva);
  3518. $sql .= ", ".price2num($this->multicurrency_total_ttc);
  3519. $sql .= ')';
  3520. $resql = $this->db->query($sql);
  3521. if ($resql) {
  3522. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  3523. $this->rowid = $this->id; // backward compatibility
  3524. if (!$error) {
  3525. $result = $this->insertExtraFields();
  3526. if ($result < 0) {
  3527. $error++;
  3528. }
  3529. }
  3530. // Si fk_remise_except defini, on lie la remise a la facture
  3531. // ce qui la flague comme "consommee".
  3532. if ($this->fk_remise_except) {
  3533. $discount = new DiscountAbsolute($this->db);
  3534. $result = $discount->fetch($this->fk_remise_except);
  3535. if ($result >= 0) {
  3536. // Check if discount was found
  3537. if ($result > 0) {
  3538. // Check if discount not already affected to another invoice
  3539. if ($discount->fk_facture_line > 0) {
  3540. if (empty($noerrorifdiscountalreadylinked)) {
  3541. $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
  3542. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  3543. $this->db->rollback();
  3544. return -3;
  3545. }
  3546. } else {
  3547. $result = $discount->link_to_invoice($this->rowid, 0);
  3548. if ($result < 0) {
  3549. $this->error = $discount->error;
  3550. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  3551. $this->db->rollback();
  3552. return -3;
  3553. }
  3554. }
  3555. } else {
  3556. $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
  3557. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  3558. $this->db->rollback();
  3559. return -3;
  3560. }
  3561. } else {
  3562. $this->error = $discount->error;
  3563. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  3564. $this->db->rollback();
  3565. return -3;
  3566. }
  3567. }
  3568. if (!$error && !$notrigger) {
  3569. // Call trigger
  3570. $result = $this->call_trigger('LINEBILL_SUPPLIER_CREATE', $user);
  3571. if ($result < 0) {
  3572. $this->db->rollback();
  3573. return -2;
  3574. }
  3575. // End call triggers
  3576. }
  3577. $this->db->commit();
  3578. return $this->id;
  3579. } else {
  3580. $this->error = $this->db->error();
  3581. $this->db->rollback();
  3582. return -2;
  3583. }
  3584. }
  3585. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3586. /**
  3587. * Mise a jour de l'objet ligne de commande en base
  3588. *
  3589. * @return int <0 si ko, >0 si ok
  3590. */
  3591. public function update_total()
  3592. {
  3593. // phpcs:enable
  3594. $this->db->begin();
  3595. // Mise a jour ligne en base
  3596. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET";
  3597. $sql .= " total_ht = ".price2num($this->total_ht);
  3598. $sql .= ", tva= ".price2num($this->total_tva);
  3599. $sql .= ", total_localtax1 = ".price2num($this->total_localtax1);
  3600. $sql .= ", total_localtax2 = ".price2num($this->total_localtax2);
  3601. $sql .= ", total_ttc = ".price2num($this->total_ttc);
  3602. $sql .= " WHERE rowid = ".((int) $this->rowid);
  3603. dol_syslog("FactureFournisseurLigne.class.php::update_total", LOG_DEBUG);
  3604. $resql = $this->db->query($sql);
  3605. if ($resql) {
  3606. $this->db->commit();
  3607. return 1;
  3608. } else {
  3609. $this->error = $this->db->error();
  3610. $this->db->rollback();
  3611. return -2;
  3612. }
  3613. }
  3614. }