fournisseur.facture.class.php 143 KB

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