fournisseur.facture.class.php 134 KB

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