fournisseur.facture.class.php 134 KB

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