supplier_proposal.class.php 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417
  1. <?php
  2. /* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  4. * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2005 Marc Barilley <marc@ocebo.com>
  6. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  7. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  8. * Copyright (C) 2008 Raphael Bertrand <raphael.bertrand@resultic.fr>
  9. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  10. * Copyright (C) 2010-2018 Philippe Grand <philippe.grand@atoo-net.com>
  11. * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
  12. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  13. * Copyright (C) 2014 Marcos García <marcosgdf@gmail.com>
  14. * Copyright (C) 2016 Ferran Marcet <fmarcet@2byte.es>
  15. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  16. * Copyright (C) 2019-2023 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2020 Tobias Sekan <tobias.sekan@startmail.com>
  18. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/supplier_proposal/class/supplier_proposal.class.php
  35. * \brief File of class to manage supplier proposals
  36. */
  37. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
  42. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  43. require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
  44. /**
  45. * Class to manage price ask supplier
  46. */
  47. class SupplierProposal extends CommonObject
  48. {
  49. use CommonIncoterm;
  50. /**
  51. * @var string ID to identify managed object
  52. */
  53. public $element = 'supplier_proposal';
  54. /**
  55. * @var string Name of table without prefix where object is stored
  56. */
  57. public $table_element = 'supplier_proposal';
  58. /**
  59. * @var string Name of subtable line
  60. */
  61. public $table_element_line = 'supplier_proposaldet';
  62. /**
  63. * @var string Field with ID of parent key if this field has a parent
  64. */
  65. public $fk_element = 'fk_supplier_proposal';
  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_proposal';
  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. public $socid; // Id client
  85. /**
  86. * @deprecated
  87. * @see $user_author_id
  88. */
  89. public $author;
  90. public $ref_fourn; //Reference saisie lors de l'ajout d'une ligne à la demande
  91. public $ref_supplier; //Reference saisie lors de l'ajout d'une ligne à la demande
  92. /**
  93. * @deprecated
  94. */
  95. public $statut; // 0 (draft), 1 (validated), 2 (signed), 3 (not signed), 4 (processed/billed)
  96. /**
  97. * @var integer|string Date of proposal
  98. */
  99. public $date;
  100. /**
  101. * @var integer|string date_livraison
  102. */
  103. public $delivery_date;
  104. /**
  105. * @deprecated
  106. * @see $date_creation
  107. */
  108. public $datec;
  109. /**
  110. * @var integer|string date_creation
  111. */
  112. public $date_creation;
  113. /**
  114. * @deprecated
  115. * @see $date_validation
  116. */
  117. public $datev;
  118. /**
  119. * @var integer|string date_validation
  120. */
  121. public $date_validation;
  122. public $user_author_id;
  123. /**
  124. * @deprecated
  125. * @see $price_ht
  126. */
  127. public $price;
  128. /**
  129. * @deprecated
  130. * @see $total_tva
  131. */
  132. public $tva;
  133. /**
  134. * @deprecated
  135. * @see $total_ttc
  136. */
  137. public $total;
  138. public $cond_reglement_code;
  139. public $mode_reglement_code;
  140. public $extraparams = array();
  141. public $lines = array();
  142. public $line;
  143. public $labelStatus = array();
  144. public $labelStatusShort = array();
  145. public $nbtodo;
  146. public $nbtodolate;
  147. // Multicurrency
  148. /**
  149. * @var int ID
  150. */
  151. public $fk_multicurrency;
  152. public $multicurrency_code;
  153. public $multicurrency_tx;
  154. public $multicurrency_total_ht;
  155. public $multicurrency_total_tva;
  156. public $multicurrency_total_ttc;
  157. /**
  158. * Draft status
  159. */
  160. const STATUS_DRAFT = 0;
  161. /**
  162. * Validated status
  163. */
  164. const STATUS_VALIDATED = 1;
  165. /**
  166. * Signed quote
  167. */
  168. const STATUS_SIGNED = 2;
  169. /**
  170. * Not signed quote, canceled
  171. */
  172. const STATUS_NOTSIGNED = 3;
  173. /**
  174. * Billed or closed/processed quote
  175. */
  176. const STATUS_CLOSE = 4;
  177. /**
  178. * Constructor
  179. *
  180. * @param DoliDB $db Database handler
  181. * @param int $socid Id third party
  182. * @param int $supplier_proposalid Id supplier_proposal
  183. */
  184. public function __construct($db, $socid = "", $supplier_proposalid = 0)
  185. {
  186. global $conf, $langs;
  187. $this->db = $db;
  188. $this->socid = $socid;
  189. $this->id = $supplier_proposalid;
  190. }
  191. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  192. /**
  193. * Add line into array ->lines
  194. *
  195. * @param int $idproduct Product Id to add
  196. * @param int $qty Quantity
  197. * @param int $remise_percent Discount effected on Product
  198. * @return int <0 if KO, >0 if OK
  199. *
  200. * TODO Remplacer les appels a cette fonction par generation objet Ligne
  201. */
  202. public function add_product($idproduct, $qty, $remise_percent = 0)
  203. {
  204. // phpcs:enable
  205. global $conf, $mysoc;
  206. if (!$qty) {
  207. $qty = 1;
  208. }
  209. dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent");
  210. if ($idproduct > 0) {
  211. $prod = new Product($this->db);
  212. $prod->fetch($idproduct);
  213. $productdesc = $prod->description;
  214. $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id);
  215. $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
  216. if (empty($tva_tx)) {
  217. $tva_npr = 0;
  218. }
  219. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr);
  220. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr);
  221. // multiprix
  222. if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) {
  223. $price = $prod->multiprices[$this->thirdparty->price_level];
  224. } else {
  225. $price = $prod->price;
  226. }
  227. $line = new SupplierProposalLine($this->db);
  228. $line->fk_product = $idproduct;
  229. $line->desc = $productdesc;
  230. $line->qty = $qty;
  231. $line->subprice = $price;
  232. $line->remise_percent = $remise_percent;
  233. $line->tva_tx = $tva_tx;
  234. $this->lines[] = $line;
  235. return 1;
  236. }
  237. return -1;
  238. }
  239. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  240. /**
  241. * Adding line of fixed discount in the proposal in DB
  242. *
  243. * @param int $idremise Id of fixed discount
  244. * @return int >0 if OK, <0 if KO
  245. */
  246. public function insert_discount($idremise)
  247. {
  248. // phpcs:enable
  249. global $langs;
  250. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  251. include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  252. $this->db->begin();
  253. $remise = new DiscountAbsolute($this->db);
  254. $result = $remise->fetch($idremise);
  255. if ($result > 0) {
  256. if ($remise->fk_facture) { // Protection against multiple submission
  257. $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
  258. $this->db->rollback();
  259. return -5;
  260. }
  261. $supplier_proposalligne = new SupplierProposalLine($this->db);
  262. $supplier_proposalligne->fk_supplier_proposal = $this->id;
  263. $supplier_proposalligne->fk_remise_except = $remise->id;
  264. $supplier_proposalligne->desc = $remise->description; // Description ligne
  265. $supplier_proposalligne->tva_tx = $remise->tva_tx;
  266. $supplier_proposalligne->subprice = -$remise->amount_ht;
  267. $supplier_proposalligne->fk_product = 0; // Id produit predefini
  268. $supplier_proposalligne->qty = 1;
  269. $supplier_proposalligne->remise_percent = 0;
  270. $supplier_proposalligne->rang = -1;
  271. $supplier_proposalligne->info_bits = 2;
  272. $supplier_proposalligne->total_ht = -$remise->amount_ht;
  273. $supplier_proposalligne->total_tva = -$remise->amount_tva;
  274. $supplier_proposalligne->total_ttc = -$remise->amount_ttc;
  275. $result = $supplier_proposalligne->insert();
  276. if ($result > 0) {
  277. $result = $this->update_price(1);
  278. if ($result > 0) {
  279. $this->db->commit();
  280. return 1;
  281. } else {
  282. $this->db->rollback();
  283. return -1;
  284. }
  285. } else {
  286. $this->error = $supplier_proposalligne->error;
  287. $this->db->rollback();
  288. return -2;
  289. }
  290. } else {
  291. $this->db->rollback();
  292. return -2;
  293. }
  294. }
  295. /**
  296. * Add a proposal line into database (linked to product/service or not)
  297. * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
  298. * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
  299. * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,'',produit)
  300. * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue)
  301. *
  302. * @param string $desc Description de la ligne
  303. * @param double $pu_ht Prix unitaire
  304. * @param double $qty Quantite
  305. * @param double $txtva Taux de tva
  306. * @param double $txlocaltax1 Local tax 1 rate
  307. * @param double $txlocaltax2 Local tax 2 rate
  308. * @param int $fk_product Product/Service ID predefined
  309. * @param double $remise_percent Percentage discount of the line
  310. * @param string $price_base_type HT or TTC
  311. * @param double $pu_ttc Prix unitaire TTC
  312. * @param int $info_bits Bits of type of lines
  313. * @param int $type Type of line (product, service)
  314. * @param int $rang Position of line
  315. * @param int $special_code Special code (also used by externals modules!)
  316. * @param int $fk_parent_line Id of parent line
  317. * @param int $fk_fournprice Id supplier price. If 0, we will take best price. If -1 we keep it empty.
  318. * @param int $pa_ht Buying price without tax
  319. * @param string $label ???
  320. * @param array $array_options extrafields array
  321. * @param string $ref_supplier Supplier price reference
  322. * @param int $fk_unit Id of the unit to use.
  323. * @param string $origin 'order', 'supplier_proposal', ...
  324. * @param int $origin_id Id of origin line
  325. * @param double $pu_ht_devise Amount in currency
  326. * @param int $date_start Date start
  327. * @param int $date_end Date end
  328. * @return int >0 if OK, <0 if KO
  329. *
  330. * @see add_product()
  331. */
  332. public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $pu_ttc = 0, $info_bits = 0, $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $array_options = 0, $ref_supplier = '', $fk_unit = '', $origin = '', $origin_id = 0, $pu_ht_devise = 0, $date_start = 0, $date_end = 0)
  333. {
  334. global $mysoc, $conf, $langs;
  335. dol_syslog(get_class($this)."::addline supplier_proposalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type");
  336. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  337. // Clean parameters
  338. if (empty($remise_percent)) {
  339. $remise_percent = 0;
  340. }
  341. if (empty($qty)) {
  342. $qty = 0;
  343. }
  344. if (empty($info_bits)) {
  345. $info_bits = 0;
  346. }
  347. if (empty($rang)) {
  348. $rang = 0;
  349. }
  350. if (empty($fk_parent_line) || $fk_parent_line < 0) {
  351. $fk_parent_line = 0;
  352. }
  353. if (empty($pu_ht)) {
  354. $pu_ht = 0;
  355. }
  356. $remise_percent = price2num($remise_percent);
  357. $qty = price2num($qty);
  358. $pu_ht = price2num($pu_ht);
  359. $pu_ttc = price2num($pu_ttc);
  360. if (!preg_match('/\((.*)\)/', $txtva)) {
  361. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  362. }
  363. $txlocaltax1 = price2num($txlocaltax1);
  364. $txlocaltax2 = price2num($txlocaltax2);
  365. $pa_ht = price2num($pa_ht);
  366. if ($price_base_type == 'HT') {
  367. $pu = $pu_ht;
  368. } else {
  369. $pu = $pu_ttc;
  370. }
  371. // Check parameters
  372. if ($type < 0) {
  373. return -1;
  374. }
  375. if ($this->statut == self::STATUS_DRAFT) {
  376. $this->db->begin();
  377. if ($fk_product > 0) {
  378. if (getDolGlobalString('SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY')) {
  379. // Check quantity is enough
  380. dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_fournprice=".$fk_fournprice." qty=".$qty." ref_supplier=".$ref_supplier);
  381. $productsupplier = new ProductFournisseur($this->db);
  382. if ($productsupplier->fetch($fk_product) > 0) {
  383. $product_type = $productsupplier->type;
  384. $label = $productsupplier->label;
  385. $fk_prod_fourn_price = $fk_fournprice;
  386. // We use 'none' instead of $ref_supplier, because fourn_ref may not exists anymore. So we will take the first supplier price ok.
  387. // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
  388. $result = $productsupplier->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
  389. if ($result > 0) {
  390. $pu = $productsupplier->fourn_pu; // Unit price supplier price set by get_buyprice
  391. $ref_supplier = $productsupplier->ref_supplier; // Ref supplier price set by get_buyprice
  392. // is remise percent not keyed but present for the product we add it
  393. if ($remise_percent == 0 && $productsupplier->remise_percent != 0) {
  394. $remise_percent = $productsupplier->remise_percent;
  395. }
  396. }
  397. if ($result == 0) { // If result == 0, we failed to found the supplier reference price
  398. $langs->load("errors");
  399. $this->error = "Ref ".$productsupplier->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
  400. $this->db->rollback();
  401. dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
  402. //$pu = $productsupplier->fourn_pu; // We do not overwrite unit price
  403. //$ref = $productsupplier_fourn; // We do not overwrite ref supplier price
  404. return -1;
  405. }
  406. if ($result == -1) {
  407. $langs->load("errors");
  408. $this->error = "Ref ".$productsupplier->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
  409. $this->db->rollback();
  410. dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
  411. return -1;
  412. }
  413. if ($result < -1) {
  414. $this->error = $productsupplier->error;
  415. $this->errors = $productsupplier->errors;
  416. $this->db->rollback();
  417. dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
  418. return -1;
  419. }
  420. } else {
  421. $this->error = $productsupplier->error;
  422. $this->errors = $productsupplier->errors;
  423. $this->db->rollback();
  424. return -1;
  425. }
  426. }
  427. } else {
  428. $product_type = $type;
  429. }
  430. // Calcul du total TTC et de la TVA pour la ligne a partir de
  431. // qty, pu, remise_percent et txtva
  432. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  433. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  434. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  435. // Clean vat code
  436. $reg = array();
  437. $vat_src_code = '';
  438. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  439. $vat_src_code = $reg[1];
  440. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  441. }
  442. if (isModEnabled("multicurrency") && $pu_ht_devise > 0) {
  443. $pu = 0;
  444. }
  445. $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_ht_devise);
  446. $total_ht = $tabprice[0];
  447. $total_tva = $tabprice[1];
  448. $total_ttc = $tabprice[2];
  449. $total_localtax1 = $tabprice[9];
  450. $total_localtax2 = $tabprice[10];
  451. $pu = $pu_ht = $tabprice[3];
  452. // MultiCurrency
  453. $multicurrency_total_ht = $tabprice[16];
  454. $multicurrency_total_tva = $tabprice[17];
  455. $multicurrency_total_ttc = $tabprice[18];
  456. $pu_ht_devise = $tabprice[19];
  457. // Rang to use
  458. $ranktouse = $rang;
  459. if ($ranktouse == -1) {
  460. $rangmax = $this->line_max($fk_parent_line);
  461. $ranktouse = $rangmax + 1;
  462. }
  463. // TODO A virer
  464. // Anciens indicateurs: $price, $remise (a ne plus utiliser)
  465. $price = $pu;
  466. $remise = 0;
  467. if ($remise_percent > 0) {
  468. $remise = round(($pu * $remise_percent / 100), 2);
  469. $price = $pu - $remise;
  470. }
  471. // Insert line
  472. $this->line = new SupplierProposalLine($this->db);
  473. $this->line->fk_supplier_proposal = $this->id;
  474. $this->line->label = $label;
  475. $this->line->desc = $desc;
  476. $this->line->qty = $qty;
  477. $this->line->vat_src_code = $vat_src_code;
  478. $this->line->tva_tx = $txtva;
  479. $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
  480. $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
  481. $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  482. $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  483. $this->line->fk_product = $fk_product;
  484. $this->line->remise_percent = $remise_percent;
  485. $this->line->subprice = $pu_ht;
  486. $this->line->rang = $ranktouse;
  487. $this->line->info_bits = $info_bits;
  488. $this->line->total_ht = $total_ht;
  489. $this->line->total_tva = $total_tva;
  490. $this->line->total_localtax1 = $total_localtax1;
  491. $this->line->total_localtax2 = $total_localtax2;
  492. $this->line->total_ttc = $total_ttc;
  493. $this->line->product_type = $type;
  494. $this->line->special_code = $special_code;
  495. $this->line->fk_parent_line = $fk_parent_line;
  496. $this->line->fk_unit = $fk_unit;
  497. $this->line->origin = $origin;
  498. $this->line->origin_id = $origin_id;
  499. $this->line->ref_fourn = $this->db->escape($ref_supplier);
  500. $this->line->date_start = $date_start;
  501. $this->line->date_end = $date_end;
  502. // infos marge
  503. if (!empty($fk_product) && $fk_product > 0 && empty($fk_fournprice) && empty($pa_ht)) {
  504. // When fk_fournprice is 0, we take the lowest buying price
  505. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  506. $productFournisseur = new ProductFournisseur($this->db);
  507. $productFournisseur->find_min_price_product_fournisseur($fk_product);
  508. $this->line->fk_fournprice = $productFournisseur->product_fourn_price_id;
  509. } else {
  510. $this->line->fk_fournprice = ($fk_fournprice > 0 ? $fk_fournprice : 0); // If fk_fournprice is -1, we will not use fk_fournprice
  511. }
  512. $this->line->pa_ht = $pa_ht;
  513. //var_dump($this->line->fk_fournprice);exit;
  514. // Multicurrency
  515. $this->line->fk_multicurrency = $this->fk_multicurrency;
  516. $this->line->multicurrency_code = $this->multicurrency_code;
  517. $this->line->multicurrency_subprice = $pu_ht_devise;
  518. $this->line->multicurrency_total_ht = $multicurrency_total_ht;
  519. $this->line->multicurrency_total_tva = $multicurrency_total_tva;
  520. $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
  521. // Mise en option de la ligne
  522. if (empty($qty) && empty($special_code)) {
  523. $this->line->special_code = 3;
  524. }
  525. if (is_array($array_options) && count($array_options) > 0) {
  526. $this->line->array_options = $array_options;
  527. }
  528. $result = $this->line->insert();
  529. if ($result > 0) {
  530. // Reorder if child line
  531. if (!empty($fk_parent_line)) {
  532. $this->line_order(true, 'DESC');
  533. } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) { // Update all rank of all other lines
  534. $linecount = count($this->lines);
  535. for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
  536. $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
  537. }
  538. }
  539. // Mise a jour informations denormalisees au niveau de la propale meme
  540. $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
  541. if ($result > 0) {
  542. $this->db->commit();
  543. return $this->line->id;
  544. } else {
  545. $this->db->rollback();
  546. return -1;
  547. }
  548. } else {
  549. $this->error = $this->line->error;
  550. $this->errors = $this->line->errors;
  551. $this->db->rollback();
  552. return -2;
  553. }
  554. } else {
  555. $this->error = 'BadStatusOfObjectToAddLine';
  556. return -5;
  557. }
  558. }
  559. /**
  560. * Update a proposal line
  561. *
  562. * @param int $rowid Id de la ligne
  563. * @param double $pu Prix unitaire (HT ou TTC selon price_base_type)
  564. * @param double $qty Quantity
  565. * @param double $remise_percent Remise effectuee sur le produit
  566. * @param double $txtva Taux de TVA
  567. * @param double $txlocaltax1 Local tax 1 rate
  568. * @param double $txlocaltax2 Local tax 2 rate
  569. * @param string $desc Description
  570. * @param double $price_base_type HT ou TTC
  571. * @param int $info_bits Miscellaneous informations
  572. * @param int $special_code Special code (also used by externals modules!)
  573. * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines).
  574. * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules)
  575. * @param int $fk_fournprice Id of origin supplier price
  576. * @param int $pa_ht Price (without tax) of product when it was bought
  577. * @param string $label ???
  578. * @param int $type 0/1=Product/service
  579. * @param array $array_options extrafields array
  580. * @param string $ref_supplier Supplier price reference
  581. * @param int $fk_unit Id of the unit to use.
  582. * @param double $pu_ht_devise Unit price in currency
  583. * @return int 0 if OK, <0 if KO
  584. */
  585. public function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $desc = '', $price_base_type = 'HT', $info_bits = 0, $special_code = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $type = 0, $array_options = 0, $ref_supplier = '', $fk_unit = '', $pu_ht_devise = 0)
  586. {
  587. global $conf, $user, $langs, $mysoc;
  588. dol_syslog(get_class($this)."::updateLine $rowid, $pu, $qty, $remise_percent, $txtva, $desc, $price_base_type, $info_bits");
  589. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  590. // Clean parameters
  591. $remise_percent = price2num($remise_percent);
  592. $qty = price2num($qty);
  593. $pu = price2num($pu);
  594. if (!preg_match('/\((.*)\)/', $txtva)) {
  595. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  596. }
  597. $txlocaltax1 = price2num($txlocaltax1);
  598. $txlocaltax2 = price2num($txlocaltax2);
  599. $pa_ht = price2num($pa_ht);
  600. if (empty($qty) && empty($special_code)) {
  601. $special_code = 3; // Set option tag
  602. }
  603. if (!empty($qty) && $special_code == 3) {
  604. $special_code = 0; // Remove option tag
  605. }
  606. if ($this->statut == 0) {
  607. $this->db->begin();
  608. // Calcul du total TTC et de la TVA pour la ligne a partir de
  609. // qty, pu, remise_percent et txtva
  610. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  611. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  612. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
  613. // Clean vat code
  614. $reg = array();
  615. $vat_src_code = '';
  616. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  617. $vat_src_code = $reg[1];
  618. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  619. }
  620. if (isModEnabled("multicurrency") && $pu_ht_devise > 0) {
  621. $pu = 0;
  622. }
  623. $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_ht_devise);
  624. $total_ht = $tabprice[0];
  625. $total_tva = $tabprice[1];
  626. $total_ttc = $tabprice[2];
  627. $total_localtax1 = $tabprice[9];
  628. $total_localtax2 = $tabprice[10];
  629. $pu_ht = $tabprice[3];
  630. $pu_tva = $tabprice[4];
  631. $pu_ttc = $tabprice[5];
  632. // MultiCurrency
  633. $multicurrency_total_ht = $tabprice[16];
  634. $multicurrency_total_tva = $tabprice[17];
  635. $multicurrency_total_ttc = $tabprice[18];
  636. $pu_ht_devise = $tabprice[19];
  637. $pu = $pu_ht;
  638. if ($price_base_type == 'TTC') {
  639. $pu = $pu_ttc;
  640. }
  641. //Fetch current line from the database and then clone the object and set it in $oldline property
  642. $line = new SupplierProposalLine($this->db);
  643. $line->fetch($rowid);
  644. $line->fetch_optionals();
  645. // Stock previous line records
  646. $staticline = clone $line;
  647. $line->oldline = $staticline;
  648. $this->line = $line;
  649. $this->line->context = $this->context;
  650. // Reorder if fk_parent_line change
  651. if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
  652. $rangmax = $this->line_max($fk_parent_line);
  653. $this->line->rang = $rangmax + 1;
  654. }
  655. $this->line->id = $rowid;
  656. $this->line->label = $label;
  657. $this->line->desc = $desc;
  658. $this->line->qty = $qty;
  659. $this->line->product_type = $type;
  660. $this->line->vat_src_code = $vat_src_code;
  661. $this->line->tva_tx = $txtva;
  662. $this->line->localtax1_tx = $txlocaltax1;
  663. $this->line->localtax2_tx = $txlocaltax2;
  664. $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  665. $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  666. $this->line->remise_percent = $remise_percent;
  667. $this->line->subprice = $pu;
  668. $this->line->info_bits = $info_bits;
  669. $this->line->total_ht = $total_ht;
  670. $this->line->total_tva = $total_tva;
  671. $this->line->total_localtax1 = $total_localtax1;
  672. $this->line->total_localtax2 = $total_localtax2;
  673. $this->line->total_ttc = $total_ttc;
  674. $this->line->special_code = $special_code;
  675. $this->line->fk_parent_line = $fk_parent_line;
  676. $this->line->skip_update_total = $skip_update_total;
  677. $this->line->ref_fourn = $ref_supplier;
  678. $this->line->fk_unit = $fk_unit;
  679. // infos marge
  680. if (!empty($fk_product) && $fk_product > 0 && empty($fk_fournprice) && empty($pa_ht)) {
  681. // by external module, take lowest buying price
  682. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  683. $productFournisseur = new ProductFournisseur($this->db);
  684. $productFournisseur->find_min_price_product_fournisseur($fk_product);
  685. $this->line->fk_fournprice = $productFournisseur->product_fourn_price_id;
  686. } else {
  687. $this->line->fk_fournprice = $fk_fournprice;
  688. }
  689. $this->line->pa_ht = $pa_ht;
  690. if (is_array($array_options) && count($array_options) > 0) {
  691. // We replace values in this->line->array_options only for entries defined into $array_options
  692. foreach ($array_options as $key => $value) {
  693. $this->line->array_options[$key] = $array_options[$key];
  694. }
  695. }
  696. // Multicurrency
  697. $this->line->multicurrency_subprice = $pu_ht_devise;
  698. $this->line->multicurrency_total_ht = $multicurrency_total_ht;
  699. $this->line->multicurrency_total_tva = $multicurrency_total_tva;
  700. $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
  701. $result = $this->line->update();
  702. if ($result > 0) {
  703. // Reorder if child line
  704. if (!empty($fk_parent_line)) {
  705. $this->line_order(true, 'DESC');
  706. }
  707. $this->update_price(1);
  708. $this->fk_supplier_proposal = $this->id;
  709. $this->db->commit();
  710. return $result;
  711. } else {
  712. $this->error = $this->db->error();
  713. $this->db->rollback();
  714. return -1;
  715. }
  716. } else {
  717. dol_syslog(get_class($this)."::updateline Erreur -2 SupplierProposal en mode incompatible pour cette action");
  718. return -2;
  719. }
  720. }
  721. /**
  722. * Delete detail line
  723. *
  724. * @param int $lineid Id of line to delete
  725. * @return int >0 if OK, <0 if KO
  726. */
  727. public function deleteline($lineid)
  728. {
  729. if ($this->statut == 0) {
  730. $line = new SupplierProposalLine($this->db);
  731. // For triggers
  732. $line->fetch($lineid);
  733. if ($line->delete() > 0) {
  734. $this->update_price(1);
  735. return 1;
  736. } else {
  737. return -1;
  738. }
  739. } else {
  740. return -2;
  741. }
  742. }
  743. /**
  744. * Create commercial proposal into database
  745. * this->ref can be set or empty. If empty, we will use "(PROVid)"
  746. *
  747. * @param User $user User that create
  748. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  749. * @return int <0 if KO, >=0 if OK
  750. */
  751. public function create($user, $notrigger = 0)
  752. {
  753. global $langs, $conf, $mysoc, $hookmanager;
  754. $error = 0;
  755. $now = dol_now();
  756. dol_syslog(get_class($this)."::create");
  757. // Check parameters
  758. $result = $this->fetch_thirdparty();
  759. if ($result < 0) {
  760. $this->error = "Failed to fetch company";
  761. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  762. return -3;
  763. }
  764. if (!empty($this->ref)) { // We check that ref is not already used
  765. $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
  766. if ($result > 0) {
  767. $this->error = 'ErrorRefAlreadyExists';
  768. dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
  769. $this->db->rollback();
  770. return -1;
  771. }
  772. }
  773. // Set tmp vars
  774. $delivery_date = $this->delivery_date;
  775. // Multicurrency
  776. if (!empty($this->multicurrency_code)) {
  777. list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $now);
  778. }
  779. if (empty($this->fk_multicurrency)) {
  780. $this->multicurrency_code = $conf->currency;
  781. $this->fk_multicurrency = 0;
  782. $this->multicurrency_tx = 1;
  783. }
  784. $this->db->begin();
  785. // Insert into database
  786. $sql = "INSERT INTO ".MAIN_DB_PREFIX."supplier_proposal (";
  787. $sql .= "fk_soc";
  788. $sql .= ", price";
  789. $sql .= ", total_tva";
  790. $sql .= ", total_ttc";
  791. $sql .= ", datec";
  792. $sql .= ", ref";
  793. $sql .= ", fk_user_author";
  794. $sql .= ", note_private";
  795. $sql .= ", note_public";
  796. $sql .= ", model_pdf";
  797. $sql .= ", fk_cond_reglement";
  798. $sql .= ", fk_mode_reglement";
  799. $sql .= ", fk_account";
  800. $sql .= ", date_livraison";
  801. $sql .= ", fk_shipping_method";
  802. $sql .= ", fk_projet";
  803. $sql .= ", entity";
  804. $sql .= ", fk_multicurrency";
  805. $sql .= ", multicurrency_code";
  806. $sql .= ", multicurrency_tx";
  807. $sql .= ") ";
  808. $sql .= " VALUES (";
  809. $sql .= ((int) $this->socid);
  810. $sql .= ", 0";
  811. $sql .= ", 0";
  812. $sql .= ", 0";
  813. $sql .= ", '".$this->db->idate($now)."'";
  814. $sql .= ", '(PROV)'";
  815. $sql .= ", ".($user->id > 0 ? ((int) $user->id) : "null");
  816. $sql .= ", '".$this->db->escape($this->note_private)."'";
  817. $sql .= ", '".$this->db->escape($this->note_public)."'";
  818. $sql .= ", '".$this->db->escape($this->model_pdf)."'";
  819. $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : 'NULL');
  820. $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : 'NULL');
  821. $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
  822. $sql .= ", ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : "null");
  823. $sql .= ", ".($this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : 'NULL');
  824. $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
  825. $sql .= ", ".((int) $conf->entity);
  826. $sql .= ", ".((int) $this->fk_multicurrency);
  827. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  828. $sql .= ", ".((double) $this->multicurrency_tx);
  829. $sql .= ")";
  830. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  831. $resql = $this->db->query($sql);
  832. if ($resql) {
  833. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."supplier_proposal");
  834. if ($this->id) {
  835. $this->ref = '(PROV'.$this->id.')';
  836. $sql = 'UPDATE '.MAIN_DB_PREFIX."supplier_proposal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
  837. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  838. $resql = $this->db->query($sql);
  839. if (!$resql) {
  840. $error++;
  841. }
  842. if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
  843. $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
  844. }
  845. // Add object linked
  846. if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
  847. foreach ($this->linked_objects as $origin => $tmp_origin_id) {
  848. 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, ...))
  849. foreach ($tmp_origin_id as $origin_id) {
  850. $ret = $this->add_object_linked($origin, $origin_id);
  851. if (!$ret) {
  852. dol_print_error($this->db);
  853. $error++;
  854. }
  855. }
  856. }
  857. }
  858. }
  859. /*
  860. * Insertion du detail des produits dans la base
  861. */
  862. if (!$error) {
  863. $fk_parent_line = 0;
  864. $num = count($this->lines);
  865. for ($i = 0; $i < $num; $i++) {
  866. // Reset fk_parent_line for no child products and special product
  867. if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) {
  868. $fk_parent_line = 0;
  869. }
  870. $result = $this->addline(
  871. $this->lines[$i]->desc,
  872. $this->lines[$i]->subprice,
  873. $this->lines[$i]->qty,
  874. $this->lines[$i]->tva_tx,
  875. $this->lines[$i]->localtax1_tx,
  876. $this->lines[$i]->localtax2_tx,
  877. $this->lines[$i]->fk_product,
  878. $this->lines[$i]->remise_percent,
  879. 'HT',
  880. 0,
  881. 0,
  882. $this->lines[$i]->product_type,
  883. $this->lines[$i]->rang,
  884. $this->lines[$i]->special_code,
  885. $fk_parent_line,
  886. $this->lines[$i]->fk_fournprice,
  887. $this->lines[$i]->pa_ht,
  888. empty($this->lines[$i]->label) ? '' : $this->lines[$i]->label, // deprecated
  889. $this->lines[$i]->array_options,
  890. $this->lines[$i]->ref_fourn,
  891. $this->lines[$i]->fk_unit,
  892. 'supplier_proposal',
  893. $this->lines[$i]->rowid
  894. );
  895. if ($result < 0) {
  896. $error++;
  897. $this->error = $this->db->error;
  898. dol_print_error($this->db);
  899. break;
  900. }
  901. // Defined the new fk_parent_line
  902. if ($result > 0 && $this->lines[$i]->product_type == 9) {
  903. $fk_parent_line = $result;
  904. }
  905. }
  906. }
  907. if (!$error) {
  908. // Mise a jour infos denormalisees
  909. $resql = $this->update_price(1);
  910. if ($resql) {
  911. $action = 'update';
  912. // Actions on extra fields
  913. if (!$error) {
  914. $result = $this->insertExtraFields();
  915. if ($result < 0) {
  916. $error++;
  917. }
  918. }
  919. if (!$error && !$notrigger) {
  920. // Call trigger
  921. $result = $this->call_trigger('PROPOSAL_SUPPLIER_CREATE', $user);
  922. if ($result < 0) {
  923. $error++;
  924. }
  925. // End call triggers
  926. }
  927. } else {
  928. $this->error = $this->db->lasterror();
  929. $error++;
  930. }
  931. }
  932. } else {
  933. $this->error = $this->db->lasterror();
  934. $error++;
  935. }
  936. if (!$error) {
  937. $this->db->commit();
  938. dol_syslog(get_class($this)."::create done id=".$this->id);
  939. return $this->id;
  940. } else {
  941. $this->db->rollback();
  942. return -2;
  943. }
  944. } else {
  945. $this->error = $this->db->lasterror();
  946. $this->db->rollback();
  947. return -1;
  948. }
  949. }
  950. /**
  951. * Load an object from its id and create a new one in database
  952. *
  953. * @param User $user User making the clone
  954. * @param int $fromid Id of thirdparty
  955. * @return int New id of clone
  956. */
  957. public function createFromClone(User $user, $fromid = 0)
  958. {
  959. global $conf, $hookmanager;
  960. $error = 0;
  961. $now = dol_now();
  962. $this->db->begin();
  963. // get extrafields so they will be clone
  964. foreach ($this->lines as $line) {
  965. $line->fetch_optionals();
  966. }
  967. // Load source object
  968. $objFrom = clone $this;
  969. $objsoc = new Societe($this->db);
  970. // Change socid if needed
  971. if (!empty($fromid) && $fromid != $this->socid) {
  972. if ($objsoc->fetch($fromid) > 0) {
  973. $this->socid = $objsoc->id;
  974. $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
  975. $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
  976. $this->fk_project = '';
  977. }
  978. // TODO Change product price if multi-prices
  979. } else {
  980. $objsoc->fetch($this->socid);
  981. }
  982. $this->id = 0;
  983. $this->statut = 0;
  984. if (!getDolGlobalString('SUPPLIER_PROPOSAL_ADDON') || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/" . getDolGlobalString('SUPPLIER_PROPOSAL_ADDON').".php")) {
  985. $this->error = 'ErrorSetupNotComplete';
  986. return -1;
  987. }
  988. // Clear fields
  989. $this->user_author_id = $user->id;
  990. $this->user_validation_id = 0;
  991. $this->date = $now;
  992. // Set ref
  993. require_once DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/" . getDolGlobalString('SUPPLIER_PROPOSAL_ADDON').'.php';
  994. $obj = $conf->global->SUPPLIER_PROPOSAL_ADDON;
  995. $modSupplierProposal = new $obj;
  996. $this->ref = $modSupplierProposal->getNextValue($objsoc, $this);
  997. // Create clone
  998. $this->context['createfromclone'] = 'createfromclone';
  999. $result = $this->create($user);
  1000. if ($result < 0) {
  1001. $error++;
  1002. }
  1003. if (!$error) {
  1004. // Hook of thirdparty module
  1005. if (is_object($hookmanager)) {
  1006. $parameters = array('objFrom'=>$objFrom);
  1007. $action = '';
  1008. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1009. if ($reshook < 0) {
  1010. $this->setErrorsFromObject($hookmanager);
  1011. $error++;
  1012. }
  1013. }
  1014. }
  1015. unset($this->context['createfromclone']);
  1016. // End
  1017. if (!$error) {
  1018. $this->db->commit();
  1019. return $this->id;
  1020. } else {
  1021. $this->db->rollback();
  1022. return -1;
  1023. }
  1024. }
  1025. /**
  1026. * Load a proposal from database and its ligne array
  1027. *
  1028. * @param int $rowid id of object to load
  1029. * @param string $ref Ref of proposal
  1030. * @return int >0 if OK, <0 if KO
  1031. */
  1032. public function fetch($rowid, $ref = '')
  1033. {
  1034. global $conf;
  1035. $sql = "SELECT p.rowid, p.entity, p.ref, p.fk_soc as socid";
  1036. $sql .= ", p.total_ttc, p.total_tva, p.localtax1, p.localtax2, p.total_ht";
  1037. $sql .= ", p.datec";
  1038. $sql .= ", p.date_valid as datev";
  1039. $sql .= ", p.date_livraison as delivery_date";
  1040. $sql .= ", p.model_pdf, p.extraparams";
  1041. $sql .= ", p.note_private, p.note_public";
  1042. $sql .= ", p.fk_projet as fk_project, p.fk_statut";
  1043. $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
  1044. $sql .= ", p.fk_cond_reglement";
  1045. $sql .= ", p.fk_mode_reglement";
  1046. $sql .= ', p.fk_account';
  1047. $sql .= ", p.fk_shipping_method";
  1048. $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
  1049. $sql .= ", c.label as statut_label";
  1050. $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc";
  1051. $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
  1052. $sql .= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."supplier_proposal as p";
  1053. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id';
  1054. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid';
  1055. $sql .= " WHERE p.fk_statut = c.id";
  1056. $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
  1057. if ($ref) {
  1058. $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
  1059. } else {
  1060. $sql .= " AND p.rowid = ".((int) $rowid);
  1061. }
  1062. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  1063. $resql = $this->db->query($sql);
  1064. if ($resql) {
  1065. if ($this->db->num_rows($resql)) {
  1066. $obj = $this->db->fetch_object($resql);
  1067. $this->id = $obj->rowid;
  1068. $this->entity = $obj->entity;
  1069. $this->ref = $obj->ref;
  1070. $this->total_ht = $obj->total_ht;
  1071. $this->total_tva = $obj->total_tva;
  1072. $this->total_localtax1 = $obj->localtax1;
  1073. $this->total_localtax2 = $obj->localtax2;
  1074. $this->total_ttc = $obj->total_ttc;
  1075. $this->socid = $obj->socid;
  1076. $this->fk_project = $obj->fk_project;
  1077. $this->model_pdf = $obj->model_pdf;
  1078. $this->note = $obj->note_private; // TODO deprecated
  1079. $this->note_private = $obj->note_private;
  1080. $this->note_public = $obj->note_public;
  1081. $this->statut = (int) $obj->fk_statut;
  1082. $this->status = (int) $obj->fk_statut;
  1083. $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
  1084. $this->datev = $this->db->jdate($obj->datev); // TODO deprecated
  1085. $this->date_creation = $this->db->jdate($obj->datec); // Creation date
  1086. $this->date = $this->date_creation;
  1087. $this->date_validation = $this->db->jdate($obj->datev); // Validation date
  1088. $this->delivery_date = $this->db->jdate($obj->delivery_date);
  1089. $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
  1090. $this->mode_reglement_id = $obj->fk_mode_reglement;
  1091. $this->mode_reglement_code = $obj->mode_reglement_code;
  1092. $this->mode_reglement = $obj->mode_reglement;
  1093. $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
  1094. $this->cond_reglement_id = $obj->fk_cond_reglement;
  1095. $this->cond_reglement_code = $obj->cond_reglement_code;
  1096. $this->cond_reglement = $obj->cond_reglement;
  1097. $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
  1098. $this->extraparams = (array) json_decode($obj->extraparams, true);
  1099. $this->user_author_id = $obj->fk_user_author;
  1100. $this->user_validation_id = $obj->fk_user_valid;
  1101. $this->user_closing_id = $obj->fk_user_cloture;
  1102. // Multicurrency
  1103. $this->fk_multicurrency = $obj->fk_multicurrency;
  1104. $this->multicurrency_code = $obj->multicurrency_code;
  1105. $this->multicurrency_tx = $obj->multicurrency_tx;
  1106. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  1107. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  1108. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  1109. // Retrieve all extrafield
  1110. // fetch optionals attributes and labels
  1111. $this->fetch_optionals();
  1112. $this->db->free($resql);
  1113. $this->lines = array();
  1114. // Lines of supplier proposals
  1115. $sql = "SELECT d.rowid, d.fk_supplier_proposal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,";
  1116. $sql .= " d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,";
  1117. $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,';
  1118. $sql .= ' d.ref_fourn as ref_produit_fourn,';
  1119. $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc, d.fk_unit';
  1120. $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as d";
  1121. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
  1122. $sql .= " WHERE d.fk_supplier_proposal = ".((int) $this->id);
  1123. $sql .= " ORDER by d.rang";
  1124. $result = $this->db->query($sql);
  1125. if ($result) {
  1126. $num = $this->db->num_rows($result);
  1127. $i = 0;
  1128. while ($i < $num) {
  1129. $objp = $this->db->fetch_object($result);
  1130. $line = new SupplierProposalLine($this->db);
  1131. $line->rowid = $objp->rowid; // deprecated
  1132. $line->id = $objp->rowid;
  1133. $line->fk_supplier_proposal = $objp->fk_supplier_proposal;
  1134. $line->fk_parent_line = $objp->fk_parent_line;
  1135. $line->product_type = $objp->product_type;
  1136. $line->label = $objp->custom_label;
  1137. $line->desc = $objp->description; // Description ligne
  1138. $line->qty = $objp->qty;
  1139. $line->tva_tx = $objp->tva_tx;
  1140. $line->localtax1_tx = $objp->localtax1_tx;
  1141. $line->localtax2_tx = $objp->localtax2_tx;
  1142. $line->subprice = $objp->subprice;
  1143. $line->fk_remise_except = $objp->fk_remise_except;
  1144. $line->remise_percent = $objp->remise_percent;
  1145. $line->info_bits = $objp->info_bits;
  1146. $line->total_ht = $objp->total_ht;
  1147. $line->total_tva = $objp->total_tva;
  1148. $line->total_localtax1 = $objp->total_localtax1;
  1149. $line->total_localtax2 = $objp->total_localtax2;
  1150. $line->total_ttc = $objp->total_ttc;
  1151. $line->fk_fournprice = $objp->fk_fournprice;
  1152. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
  1153. $line->pa_ht = $marginInfos[0];
  1154. $line->marge_tx = $marginInfos[1];
  1155. $line->marque_tx = $marginInfos[2];
  1156. $line->special_code = $objp->special_code;
  1157. $line->rang = $objp->rang;
  1158. $line->fk_product = $objp->fk_product;
  1159. $line->ref = $objp->product_ref; // deprecated
  1160. $line->product_ref = $objp->product_ref;
  1161. $line->libelle = $objp->product_label; // deprecated
  1162. $line->product_label = $objp->product_label;
  1163. $line->product_desc = $objp->product_desc; // Description produit
  1164. $line->fk_product_type = $objp->fk_product_type;
  1165. $line->ref_fourn = $objp->ref_produit_fourn;
  1166. // Multicurrency
  1167. $line->fk_multicurrency = $objp->fk_multicurrency;
  1168. $line->multicurrency_code = $objp->multicurrency_code;
  1169. $line->multicurrency_subprice = $objp->multicurrency_subprice;
  1170. $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
  1171. $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
  1172. $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  1173. $line->fk_unit = $objp->fk_unit;
  1174. $this->lines[$i] = $line;
  1175. $i++;
  1176. }
  1177. $this->db->free($result);
  1178. } else {
  1179. $this->error = $this->db->error();
  1180. return -1;
  1181. }
  1182. // Retrieve all extrafield
  1183. // fetch optionals attributes and labels
  1184. $this->fetch_optionals();
  1185. return 1;
  1186. }
  1187. $this->error = "Record Not Found";
  1188. return 0;
  1189. } else {
  1190. $this->error = $this->db->error();
  1191. return -1;
  1192. }
  1193. }
  1194. /**
  1195. * Set status to validated
  1196. *
  1197. * @param User $user Object user that validate
  1198. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1199. * @return int <0 if KO, >=0 if OK
  1200. */
  1201. public function valid($user, $notrigger = 0)
  1202. {
  1203. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1204. global $conf, $langs;
  1205. $error = 0;
  1206. $now = dol_now();
  1207. if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('supplier_proposal', 'creer'))
  1208. || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('supplier_proposal', 'validate_advance'))) {
  1209. $this->db->begin();
  1210. // Numbering module definition
  1211. $soc = new Societe($this->db);
  1212. $result = $soc->fetch($this->socid);
  1213. if ($result < 0) {
  1214. return -1;
  1215. }
  1216. // Define new ref
  1217. if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
  1218. $num = $this->getNextNumRef($soc);
  1219. } else {
  1220. $num = $this->ref;
  1221. }
  1222. $this->newref = dol_sanitizeFileName($num);
  1223. $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
  1224. $sql .= " SET ref = '".$this->db->escape($num)."',";
  1225. $sql .= " fk_statut = 1, date_valid='".$this->db->idate($now)."', fk_user_valid=".((int) $user->id);
  1226. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  1227. dol_syslog(get_class($this)."::valid", LOG_DEBUG);
  1228. $resql = $this->db->query($sql);
  1229. if (!$resql) {
  1230. dol_print_error($this->db);
  1231. $error++;
  1232. }
  1233. // Trigger calls
  1234. if (!$error && !$notrigger) {
  1235. // Call trigger
  1236. $result = $this->call_trigger('PROPOSAL_SUPPLIER_VALIDATE', $user);
  1237. if ($result < 0) {
  1238. $error++;
  1239. }
  1240. // End call triggers
  1241. }
  1242. if (!$error) {
  1243. $this->oldref = $this->ref;
  1244. // Rename directory if dir was a temporary ref
  1245. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  1246. // Now we rename also files into index
  1247. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'supplier_proposal/".$this->db->escape($this->newref)."'";
  1248. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'supplier_proposal/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  1249. $resql = $this->db->query($sql);
  1250. if (!$resql) {
  1251. $error++; $this->error = $this->db->lasterror();
  1252. }
  1253. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'supplier_proposal/".$this->db->escape($this->newref)."'";
  1254. $sql .= " WHERE filepath = 'supplier_proposal/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  1255. $resql = $this->db->query($sql);
  1256. if (!$resql) {
  1257. $error++; $this->error = $this->db->lasterror();
  1258. }
  1259. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  1260. $oldref = dol_sanitizeFileName($this->ref);
  1261. $newref = dol_sanitizeFileName($num);
  1262. $dirsource = $conf->supplier_proposal->dir_output.'/'.$oldref;
  1263. $dirdest = $conf->supplier_proposal->dir_output.'/'.$newref;
  1264. if (!$error && file_exists($dirsource)) {
  1265. dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
  1266. if (@rename($dirsource, $dirdest)) {
  1267. dol_syslog("Rename ok");
  1268. // Rename docs starting with $oldref with $newref
  1269. $listoffiles = dol_dir_list($conf->supplier_proposal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  1270. foreach ($listoffiles as $fileentry) {
  1271. $dirsource = $fileentry['name'];
  1272. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  1273. $dirsource = $fileentry['path'].'/'.$dirsource;
  1274. $dirdest = $fileentry['path'].'/'.$dirdest;
  1275. @rename($dirsource, $dirdest);
  1276. }
  1277. }
  1278. }
  1279. }
  1280. $this->ref = $num;
  1281. $this->statut = self::STATUS_VALIDATED;
  1282. $this->status = self::STATUS_VALIDATED;
  1283. $this->user_validation_id = $user->id;
  1284. $this->datev = $now;
  1285. $this->date_validation = $now;
  1286. $this->db->commit();
  1287. return 1;
  1288. } else {
  1289. $this->db->rollback();
  1290. return -1;
  1291. }
  1292. } else {
  1293. dol_syslog("You don't have permission to validate supplier proposal", LOG_WARNING);
  1294. return -2;
  1295. }
  1296. }
  1297. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1298. /**
  1299. * Set delivery date
  1300. *
  1301. * @param User $user Object user that modify
  1302. * @param int $delivery_date Delivery date
  1303. * @return int <0 if ko, >0 if ok
  1304. * @deprecated Use setDeliveryDate
  1305. */
  1306. public function set_date_livraison($user, $delivery_date)
  1307. {
  1308. // phpcs:enable
  1309. return $this->setDeliveryDate($user, $delivery_date);
  1310. }
  1311. /**
  1312. * Set delivery date
  1313. *
  1314. * @param User $user Object user that modify
  1315. * @param int $delivery_date Delivery date
  1316. * @return int <0 if ko, >0 if ok
  1317. */
  1318. public function setDeliveryDate($user, $delivery_date)
  1319. {
  1320. if ($user->hasRight('supplier_proposal', 'creer')) {
  1321. $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal ";
  1322. $sql .= " SET date_livraison = ".($delivery_date != '' ? "'".$this->db->idate($delivery_date)."'" : 'null');
  1323. $sql .= " WHERE rowid = ".((int) $this->id);
  1324. if ($this->db->query($sql)) {
  1325. $this->delivery_date = $delivery_date;
  1326. return 1;
  1327. } else {
  1328. $this->error = $this->db->error();
  1329. dol_syslog(get_class($this)."::setDeliveryDate Erreur SQL");
  1330. return -1;
  1331. }
  1332. }
  1333. return 0;
  1334. }
  1335. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1336. /**
  1337. * Set an overall discount on the proposal
  1338. *
  1339. * @param User $user Object user that modify
  1340. * @param double $remise Amount discount
  1341. * @return int <0 if ko, >0 if ok
  1342. */
  1343. /*
  1344. public function set_remise_percent($user, $remise)
  1345. {
  1346. // phpcs:enable
  1347. $remise = trim($remise) ?trim($remise) : 0;
  1348. if ($user->hasRight('supplier_proposal', 'creer')) {
  1349. $remise = price2num($remise, 2);
  1350. $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal SET remise_percent = ".((float) $remise);
  1351. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  1352. if ($this->db->query($sql)) {
  1353. $this->remise_percent = ((float) $remise);
  1354. $this->update_price(1);
  1355. return 1;
  1356. } else {
  1357. $this->error = $this->db->error();
  1358. return -1;
  1359. }
  1360. }
  1361. return 0;
  1362. }
  1363. */
  1364. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1365. /**
  1366. * Set an absolute overall discount on the proposal
  1367. *
  1368. * @param User $user Object user that modify
  1369. * @param double $remise Amount discount
  1370. * @return int <0 if ko, >0 if ok
  1371. */
  1372. /*
  1373. public function set_remise_absolue($user, $remise)
  1374. {
  1375. // phpcs:enable
  1376. if (empty($remise)) {
  1377. $remise = 0;
  1378. }
  1379. $remise = price2num($remise);
  1380. if ($user->hasRight('supplier_proposal', 'creer')) {
  1381. $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal ";
  1382. $sql .= " SET remise_absolue = ".((float) $remise);
  1383. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  1384. if ($this->db->query($sql)) {
  1385. $this->remise_absolue = $remise;
  1386. $this->update_price(1);
  1387. return 1;
  1388. } else {
  1389. $this->error = $this->db->error();
  1390. return -1;
  1391. }
  1392. }
  1393. return 0;
  1394. }
  1395. */
  1396. /**
  1397. * Reopen the commercial proposal
  1398. *
  1399. * @param User $user Object user that close
  1400. * @param int $statut Statut
  1401. * @param string $note Comment
  1402. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1403. * @return int <0 if KO, >0 if OK
  1404. */
  1405. public function reopen($user, $statut, $note = '', $notrigger = 0)
  1406. {
  1407. global $langs, $conf;
  1408. $this->statut = $statut;
  1409. $error = 0;
  1410. $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
  1411. $sql .= " SET fk_statut = ".((int) $this->statut).",";
  1412. if (!empty($note)) {
  1413. $sql .= " note_private = '".$this->db->escape($note)."',";
  1414. }
  1415. $sql .= " date_cloture = NULL, fk_user_cloture = NULL";
  1416. $sql .= " WHERE rowid = ".((int) $this->id);
  1417. $this->db->begin();
  1418. dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
  1419. $resql = $this->db->query($sql);
  1420. if (!$resql) {
  1421. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  1422. }
  1423. if (!$error) {
  1424. if (!$notrigger) {
  1425. // Call trigger
  1426. $result = $this->call_trigger('PROPOSAL_SUPPLIER_REOPEN', $user);
  1427. if ($result < 0) {
  1428. $error++;
  1429. }
  1430. // End call triggers
  1431. }
  1432. }
  1433. // Commit or rollback
  1434. if ($error) {
  1435. if (!empty($this->errors)) {
  1436. foreach ($this->errors as $errmsg) {
  1437. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  1438. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1439. }
  1440. }
  1441. $this->db->rollback();
  1442. return -1 * $error;
  1443. } else {
  1444. $this->db->commit();
  1445. return 1;
  1446. }
  1447. }
  1448. /**
  1449. * Close the askprice
  1450. *
  1451. * @param User $user Object user that close
  1452. * @param int $status Status
  1453. * @param string $note Comment
  1454. * @return int <0 if KO, >0 if OK
  1455. */
  1456. public function cloture($user, $status, $note)
  1457. {
  1458. global $langs, $conf;
  1459. $hidedetails = 0;
  1460. $hidedesc = 0;
  1461. $hideref = 0;
  1462. $this->statut = $status;
  1463. $error = 0;
  1464. $now = dol_now();
  1465. $this->db->begin();
  1466. $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
  1467. $sql .= " SET fk_statut = ".((int) $status).", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id;
  1468. $sql .= " WHERE rowid = ".((int) $this->id);
  1469. $resql = $this->db->query($sql);
  1470. if ($resql) {
  1471. $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED : (empty($this->model_pdf) ? '' : $this->model_pdf);
  1472. $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_REFUSED';
  1473. if ($status == 2) {
  1474. $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_SIGNED';
  1475. $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL : (empty($this->model_pdf) ? '' : $this->model_pdf);
  1476. if (getDolGlobalString('SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL')) { // TODO This option was not tested correctly. Error if product ref does not exists
  1477. $result = $this->updateOrCreatePriceFournisseur($user);
  1478. }
  1479. }
  1480. if ($status == 4) {
  1481. $triggerName = 'PROPOSAL_SUPPLIER_CLASSIFY_BILLED';
  1482. }
  1483. if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
  1484. // Define output language
  1485. $outputlangs = $langs;
  1486. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  1487. $outputlangs = new Translate("", $conf);
  1488. $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
  1489. $outputlangs->setDefaultLang($newlang);
  1490. }
  1491. //$ret=$object->fetch($id); // Reload to get new records
  1492. $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1493. }
  1494. // Call trigger
  1495. $result = $this->call_trigger($triggerName, $user);
  1496. if ($result < 0) {
  1497. $error++;
  1498. }
  1499. // End call triggers
  1500. if (!$error) {
  1501. $this->db->commit();
  1502. return 1;
  1503. } else {
  1504. $this->db->rollback();
  1505. return -1;
  1506. }
  1507. } else {
  1508. $this->error = $this->db->lasterror();
  1509. $this->errors[] = $this->db->lasterror();
  1510. $this->db->rollback();
  1511. return -1;
  1512. }
  1513. }
  1514. /**
  1515. * Add or update supplier price according to result of proposal
  1516. *
  1517. * @param User $user Object user
  1518. * @return int > 0 if OK
  1519. */
  1520. public function updateOrCreatePriceFournisseur($user)
  1521. {
  1522. global $conf;
  1523. dol_syslog(get_class($this)."::updateOrCreatePriceFournisseur", LOG_DEBUG);
  1524. foreach ($this->lines as $product) {
  1525. if ($product->subprice <= 0) {
  1526. continue;
  1527. }
  1528. $productsupplier = new ProductFournisseur($this->db);
  1529. $multicurrency_tx = 1;
  1530. $fk_multicurrency = 0;
  1531. if (empty($this->thirdparty)) {
  1532. $this->fetch_thirdparty();
  1533. }
  1534. $ref_fourn = $product->ref_fourn;
  1535. if (empty($ref_fourn)) {
  1536. $ref_fourn = $product->ref_supplier;
  1537. }
  1538. if (isModEnabled("multicurrency") && !empty($product->multicurrency_code)) {
  1539. list($fk_multicurrency, $multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $product->multicurrency_code);
  1540. }
  1541. $productsupplier->id = $product->fk_product;
  1542. $productsupplier->update_buyprice($product->qty, $product->total_ht, $user, 'HT', $this->thirdparty, '', $ref_fourn, $product->tva_tx, 0, 0, 0, $product->info_bits, '', '', array(), '', $product->multicurrency_total_ht, 'HT', $multicurrency_tx, $product->multicurrency_code, '', '', '');
  1543. }
  1544. return 1;
  1545. }
  1546. /**
  1547. * Upate ProductFournisseur
  1548. *
  1549. * @param int $idProductFournPrice id of llx_product_fournisseur_price
  1550. * @param Product $product contain informations to update
  1551. * @param User $user Object user
  1552. * @return int <0 if KO, >0 if OK
  1553. */
  1554. public function updatePriceFournisseur($idProductFournPrice, $product, $user)
  1555. {
  1556. $price = price2num($product->subprice * $product->qty, 'MU');
  1557. $unitPrice = price2num($product->subprice, 'MU');
  1558. $sql = 'UPDATE '.MAIN_DB_PREFIX.'product_fournisseur_price SET '.(!empty($product->ref_fourn) ? 'ref_fourn = "'.$this->db->escape($product->ref_fourn).'", ' : '').' price ='.((float) $price).', unitprice ='.((float) $unitPrice).' WHERE rowid = '.((int) $idProductFournPrice);
  1559. $resql = $this->db->query($sql);
  1560. if (!$resql) {
  1561. $this->error = $this->db->error();
  1562. $this->db->rollback();
  1563. return -1;
  1564. }
  1565. return 1;
  1566. }
  1567. /**
  1568. * Create ProductFournisseur
  1569. *
  1570. * @param Product $product Object Product
  1571. * @param User $user Object user
  1572. * @return int <0 if KO, >0 if OK
  1573. */
  1574. public function createPriceFournisseur($product, $user)
  1575. {
  1576. global $conf;
  1577. $price = price2num($product->subprice * $product->qty, 'MU');
  1578. $qty = price2num($product->qty);
  1579. $unitPrice = price2num($product->subprice, 'MU');
  1580. $now = dol_now();
  1581. $values = array(
  1582. "'".$this->db->idate($now)."'",
  1583. $product->fk_product,
  1584. $this->thirdparty->id,
  1585. "'".$product->ref_fourn."'",
  1586. $price,
  1587. $qty,
  1588. $unitPrice,
  1589. $product->tva_tx,
  1590. $user->id
  1591. );
  1592. if (isModEnabled("multicurrency")) {
  1593. if (!empty($product->multicurrency_code)) {
  1594. include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  1595. $multicurrency = new MultiCurrency($this->db); //need to fetch because empty fk_multicurrency and rate
  1596. $multicurrency->fetch(0, $product->multicurrency_code);
  1597. if (!empty($multicurrency->id)) {
  1598. $values[] = $multicurrency->id;
  1599. $values[] = "'".$product->multicurrency_code."'";
  1600. $values[] = $product->multicurrency_subprice;
  1601. $values[] = $product->multicurrency_total_ht;
  1602. $values[] = $multicurrency->rate->rate;
  1603. } else {
  1604. for ($i = 0; $i < 5; $i++) {
  1605. $values[] = 'NULL';
  1606. }
  1607. }
  1608. }
  1609. }
  1610. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'product_fournisseur_price ';
  1611. $sql .= '(datec, fk_product, fk_soc, ref_fourn, price, quantity, unitprice, tva_tx, fk_user';
  1612. if (isModEnabled("multicurrency") && !empty($product->multicurrency_code)) {
  1613. $sql .= ',fk_multicurrency, multicurrency_code, multicurrency_unitprice, multicurrency_price, multicurrency_tx';
  1614. }
  1615. $sql .= ') VALUES ('.implode(',', $values).')';
  1616. $resql = $this->db->query($sql);
  1617. if (!$resql) {
  1618. $this->error = $this->db->error();
  1619. $this->db->rollback();
  1620. return -1;
  1621. }
  1622. return 1;
  1623. }
  1624. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1625. /**
  1626. * Set draft status
  1627. *
  1628. * @param User $user Object user that modify
  1629. * @return int <0 if KO, >0 if OK
  1630. */
  1631. public function setDraft($user)
  1632. {
  1633. // phpcs:enable
  1634. global $conf, $langs;
  1635. $error = 0;
  1636. if ($this->statut == self::STATUS_DRAFT) {
  1637. dol_syslog(get_class($this)."::setDraft already draft status", LOG_WARNING);
  1638. return 0;
  1639. }
  1640. $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
  1641. $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
  1642. $sql .= " WHERE rowid = ".((int) $this->id);
  1643. if ($this->db->query($sql)) {
  1644. if (!$error) {
  1645. $this->oldcopy = clone $this;
  1646. }
  1647. if (!$error) {
  1648. // Call trigger
  1649. $result = $this->call_trigger('PROPOSAL_SUPPLIER_UNVALIDATE', $user);
  1650. if ($result < 0) {
  1651. $error++;
  1652. }
  1653. }
  1654. if (!$error) {
  1655. $this->status = self::STATUS_DRAFT;
  1656. $this->statut = self::STATUS_DRAFT; // dperecated
  1657. $this->db->commit();
  1658. return 1;
  1659. } else {
  1660. $this->db->rollback();
  1661. return -1;
  1662. }
  1663. } else {
  1664. return -1;
  1665. }
  1666. }
  1667. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1668. /**
  1669. * Return list of askprice (eventually filtered on user) into an array
  1670. *
  1671. * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
  1672. * @param int $draft 0=not draft, 1=draft
  1673. * @param int $notcurrentuser 0=all user, 1=not current user
  1674. * @param int $socid Id third pary
  1675. * @param int $limit For pagination
  1676. * @param int $offset For pagination
  1677. * @param string $sortfield Sort criteria
  1678. * @param string $sortorder Sort order
  1679. * @return array|int -1 if KO, array with result if OK
  1680. */
  1681. public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datec', $sortorder = 'DESC')
  1682. {
  1683. // phpcs:enable
  1684. global $conf, $user;
  1685. $ga = array();
  1686. $sql = "SELECT s.rowid, s.nom as name, s.client,";
  1687. $sql .= " p.rowid as supplier_proposalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
  1688. $sql .= " p.datep as dp, p.fin_validite as datelimite";
  1689. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  1690. $sql .= ", sc.fk_soc, sc.fk_user";
  1691. }
  1692. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."c_propalst as c";
  1693. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  1694. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  1695. }
  1696. $sql .= " WHERE p.entity IN (".getEntity('supplier_proposal').")";
  1697. $sql .= " AND p.fk_soc = s.rowid";
  1698. $sql .= " AND p.fk_statut = c.id";
  1699. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) { //restriction
  1700. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1701. }
  1702. if ($socid) {
  1703. $sql .= " AND s.rowid = ".((int) $socid);
  1704. }
  1705. if ($draft) {
  1706. $sql .= " AND p.fk_statut = 0";
  1707. }
  1708. if ($notcurrentuser > 0) {
  1709. $sql .= " AND p.fk_user_author <> ".$user->id;
  1710. }
  1711. $sql .= $this->db->order($sortfield, $sortorder);
  1712. $sql .= $this->db->plimit($limit, $offset);
  1713. $result = $this->db->query($sql);
  1714. if ($result) {
  1715. $num = $this->db->num_rows($result);
  1716. if ($num) {
  1717. $i = 0;
  1718. while ($i < $num) {
  1719. $obj = $this->db->fetch_object($result);
  1720. if ($shortlist == 1) {
  1721. $ga[$obj->supplier_proposalid] = $obj->ref;
  1722. } elseif ($shortlist == 2) {
  1723. $ga[$obj->supplier_proposalid] = $obj->ref.' ('.$obj->name.')';
  1724. } else {
  1725. $ga[$i]['id'] = $obj->supplier_proposalid;
  1726. $ga[$i]['ref'] = $obj->ref;
  1727. $ga[$i]['name'] = $obj->name;
  1728. }
  1729. $i++;
  1730. }
  1731. }
  1732. return $ga;
  1733. } else {
  1734. dol_print_error($this->db);
  1735. return -1;
  1736. }
  1737. }
  1738. /**
  1739. * Delete askprice
  1740. *
  1741. * @param User $user Object user that delete
  1742. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1743. * @return int 1 if ok, otherwise if error
  1744. */
  1745. public function delete($user, $notrigger = 0)
  1746. {
  1747. global $conf, $langs;
  1748. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1749. $error = 0;
  1750. $this->db->begin();
  1751. if (!$notrigger) {
  1752. // Call trigger
  1753. $result = $this->call_trigger('PROPOSAL_SUPPLIER_DELETE', $user);
  1754. if ($result < 0) {
  1755. $error++;
  1756. }
  1757. // End call triggers
  1758. }
  1759. if (!$error) {
  1760. $main = MAIN_DB_PREFIX.'supplier_proposaldet';
  1761. $ef = $main."_extrafields";
  1762. $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_supplier_proposal = ".((int) $this->id).")";
  1763. $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal = ".((int) $this->id);
  1764. if ($this->db->query($sql)) {
  1765. $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal WHERE rowid = ".((int) $this->id);
  1766. if ($this->db->query($sqlef) && $this->db->query($sql)) {
  1767. // Delete linked object
  1768. $res = $this->deleteObjectLinked();
  1769. if ($res < 0) {
  1770. $error++;
  1771. }
  1772. if (!$error) {
  1773. // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
  1774. $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
  1775. $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  1776. // We remove directory
  1777. $ref = dol_sanitizeFileName($this->ref);
  1778. if ($conf->supplier_proposal->dir_output && !empty($this->ref)) {
  1779. $dir = $conf->supplier_proposal->dir_output."/".$ref;
  1780. $file = $dir."/".$ref.".pdf";
  1781. if (file_exists($file)) {
  1782. dol_delete_preview($this);
  1783. if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
  1784. $this->error = 'ErrorFailToDeleteFile';
  1785. $this->errors = array('ErrorFailToDeleteFile');
  1786. $this->db->rollback();
  1787. return 0;
  1788. }
  1789. }
  1790. if (file_exists($dir)) {
  1791. $res = @dol_delete_dir_recursive($dir);
  1792. if (!$res) {
  1793. $this->error = 'ErrorFailToDeleteDir';
  1794. $this->errors = array('ErrorFailToDeleteDir');
  1795. $this->db->rollback();
  1796. return 0;
  1797. }
  1798. }
  1799. }
  1800. }
  1801. // Removed extrafields
  1802. if (!$error) {
  1803. $result = $this->deleteExtraFields();
  1804. if ($result < 0) {
  1805. $error++;
  1806. $errorflag = -4;
  1807. dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR);
  1808. }
  1809. }
  1810. if (!$error) {
  1811. dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
  1812. $this->db->commit();
  1813. return 1;
  1814. } else {
  1815. $this->error = $this->db->lasterror();
  1816. $this->db->rollback();
  1817. return 0;
  1818. }
  1819. } else {
  1820. $this->error = $this->db->lasterror();
  1821. $this->db->rollback();
  1822. return -3;
  1823. }
  1824. } else {
  1825. $this->error = $this->db->lasterror();
  1826. $this->db->rollback();
  1827. return -2;
  1828. }
  1829. } else {
  1830. $this->db->rollback();
  1831. return -1;
  1832. }
  1833. }
  1834. /**
  1835. * Object SupplierProposal Information
  1836. *
  1837. * @param int $id Proposal id
  1838. * @return void
  1839. */
  1840. public function info($id)
  1841. {
  1842. $sql = "SELECT c.rowid, ";
  1843. $sql .= " c.datec, c.date_valid as datev, c.date_cloture as dateo,";
  1844. $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture";
  1845. $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as c";
  1846. $sql .= " WHERE c.rowid = ".((int) $id);
  1847. $result = $this->db->query($sql);
  1848. if ($result) {
  1849. if ($this->db->num_rows($result)) {
  1850. $obj = $this->db->fetch_object($result);
  1851. $this->id = $obj->rowid;
  1852. $this->date_creation = $this->db->jdate($obj->datec);
  1853. $this->date_validation = $this->db->jdate($obj->datev);
  1854. $this->date_cloture = $this->db->jdate($obj->dateo);
  1855. $this->user_creation_id = $obj->fk_user_author;
  1856. $this->user_validation_id = $obj->fk_user_valid;
  1857. $this->user_closing_id = $obj->fk_user_cloture;
  1858. }
  1859. $this->db->free($result);
  1860. } else {
  1861. dol_print_error($this->db);
  1862. }
  1863. }
  1864. /**
  1865. * Return label of status of proposal (draft, validated, ...)
  1866. *
  1867. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  1868. * @return string Label
  1869. */
  1870. public function getLibStatut($mode = 0)
  1871. {
  1872. return $this->LibStatut((isset($this->statut) ? $this->statut : $this->status), $mode);
  1873. }
  1874. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1875. /**
  1876. * Return label of a status (draft, validated, ...)
  1877. *
  1878. * @param int $status Id status
  1879. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1880. * @return string Label
  1881. */
  1882. public function LibStatut($status, $mode = 1)
  1883. {
  1884. // phpcs:enable
  1885. // Init/load array of translation of status
  1886. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  1887. global $langs;
  1888. $langs->load("supplier_proposal");
  1889. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv("SupplierProposalStatusDraft");
  1890. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv("SupplierProposalStatusValidated");
  1891. $this->labelStatus[self::STATUS_SIGNED] = $langs->transnoentitiesnoconv("SupplierProposalStatusSigned");
  1892. $this->labelStatus[self::STATUS_NOTSIGNED] = $langs->transnoentitiesnoconv("SupplierProposalStatusNotSigned");
  1893. $this->labelStatus[self::STATUS_CLOSE] = $langs->transnoentitiesnoconv("SupplierProposalStatusClosed");
  1894. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv("SupplierProposalStatusDraftShort");
  1895. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv("SupplierProposalStatusValidatedShort");
  1896. $this->labelStatusShort[self::STATUS_SIGNED] = $langs->transnoentitiesnoconv("SupplierProposalStatusSignedShort");
  1897. $this->labelStatusShort[self::STATUS_NOTSIGNED] = $langs->transnoentitiesnoconv("SupplierProposalStatusNotSignedShort");
  1898. $this->labelStatusShort[self::STATUS_CLOSE] = $langs->transnoentitiesnoconv("SupplierProposalStatusClosedShort");
  1899. }
  1900. $statusnew = '';
  1901. if ($status == self::STATUS_DRAFT) {
  1902. $statusnew = 'status0';
  1903. } elseif ($status == self::STATUS_VALIDATED) {
  1904. $statusnew = 'status1';
  1905. } elseif ($status == self::STATUS_SIGNED) {
  1906. $statusnew = 'status4';
  1907. } elseif ($status == self::STATUS_NOTSIGNED) {
  1908. $statusnew = 'status9';
  1909. } elseif ($status == self::STATUS_CLOSE) {
  1910. $statusnew = 'status6';
  1911. }
  1912. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusnew, $mode);
  1913. }
  1914. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1915. /**
  1916. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1917. *
  1918. * @param User $user Object user
  1919. * @param string $mode "opened" for askprice to close, "signed" for proposal to invoice
  1920. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  1921. */
  1922. public function load_board($user, $mode)
  1923. {
  1924. // phpcs:enable
  1925. global $conf, $user, $langs;
  1926. $now = dol_now();
  1927. $clause = " WHERE";
  1928. $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.date_cloture as datefin";
  1929. $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p";
  1930. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  1931. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
  1932. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  1933. $clause = " AND";
  1934. }
  1935. $sql .= $clause." p.entity IN (".getEntity('supplier_proposal').")";
  1936. if ($mode == 'opened') {
  1937. $sql .= " AND p.fk_statut = 1";
  1938. }
  1939. if ($mode == 'signed') {
  1940. $sql .= " AND p.fk_statut = 2";
  1941. }
  1942. if ($user->socid) {
  1943. $sql .= " AND p.fk_soc = ".((int) $user->socid);
  1944. }
  1945. $resql = $this->db->query($sql);
  1946. if ($resql) {
  1947. $label = $labelShort = '';
  1948. $status = '';
  1949. if ($mode == 'opened') {
  1950. $delay_warning = !empty($conf->supplier_proposal->cloture->warning_delay) ? $conf->supplier_proposal->cloture->warning_delay : 0;
  1951. $status = self::STATUS_VALIDATED;
  1952. $label = $langs->trans("SupplierProposalsToClose");
  1953. $labelShort = $langs->trans("ToAcceptRefuse");
  1954. }
  1955. if ($mode == 'signed') {
  1956. $delay_warning = !empty($conf->supplier_proposal->facturation->warning_delay) ? $conf->supplier_proposal->facturation->warning_delay : 0;
  1957. $status = self::STATUS_SIGNED;
  1958. $label = $langs->trans("SupplierProposalsToProcess"); // May be billed or ordered
  1959. $labelShort = $langs->trans("ToClose");
  1960. }
  1961. $response = new WorkboardResponse();
  1962. $response->warning_delay = $delay_warning / 60 / 60 / 24;
  1963. $response->label = $label;
  1964. $response->labelShort = $labelShort;
  1965. $response->url = DOL_URL_ROOT.'/supplier_proposal/list.php?search_status='.$status;
  1966. $response->img = img_object('', "propal");
  1967. // This assignment in condition is not a bug. It allows walking the results.
  1968. while ($obj = $this->db->fetch_object($resql)) {
  1969. $response->nbtodo++;
  1970. if ($mode == 'opened') {
  1971. $datelimit = $this->db->jdate($obj->datefin);
  1972. if ($datelimit < ($now - $delay_warning)) {
  1973. $response->nbtodolate++;
  1974. }
  1975. }
  1976. // TODO Definir regle des propales a facturer en retard
  1977. // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++;
  1978. }
  1979. return $response;
  1980. } else {
  1981. $this->error = $this->db->lasterror();
  1982. return -1;
  1983. }
  1984. }
  1985. /**
  1986. * Initialise an instance with random values.
  1987. * Used to build previews or test instances.
  1988. * id must be 0 if object instance is a specimen.
  1989. *
  1990. * @return void
  1991. */
  1992. public function initAsSpecimen()
  1993. {
  1994. global $user, $langs, $conf;
  1995. // Load array of products prodids
  1996. $num_prods = 0;
  1997. $prodids = array();
  1998. $sql = "SELECT rowid";
  1999. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  2000. $sql .= " WHERE entity IN (".getEntity('product').")";
  2001. $sql .= $this->db->plimit(100);
  2002. $resql = $this->db->query($sql);
  2003. if ($resql) {
  2004. $num_prods = $this->db->num_rows($resql);
  2005. $i = 0;
  2006. while ($i < $num_prods) {
  2007. $i++;
  2008. $row = $this->db->fetch_row($resql);
  2009. $prodids[$i] = $row[0];
  2010. }
  2011. }
  2012. // Initialise parametres
  2013. $this->id = 0;
  2014. $this->ref = 'SPECIMEN';
  2015. $this->specimen = 1;
  2016. $this->socid = 1;
  2017. $this->date = time();
  2018. $this->cond_reglement_id = 1;
  2019. $this->cond_reglement_code = 'RECEP';
  2020. $this->mode_reglement_id = 7;
  2021. $this->mode_reglement_code = 'CHQ';
  2022. $this->note_public = 'This is a comment (public)';
  2023. $this->note_private = 'This is a comment (private)';
  2024. // Lines
  2025. $nbp = 5;
  2026. $xnbp = 0;
  2027. while ($xnbp < $nbp) {
  2028. $line = new SupplierProposalLine($this->db);
  2029. $line->desc = $langs->trans("Description")." ".$xnbp;
  2030. $line->qty = 1;
  2031. $line->subprice = 100;
  2032. $line->tva_tx = 19.6;
  2033. $line->localtax1_tx = 0;
  2034. $line->localtax2_tx = 0;
  2035. if ($xnbp == 2) {
  2036. $line->total_ht = 50;
  2037. $line->total_ttc = 59.8;
  2038. $line->total_tva = 9.8;
  2039. $line->remise_percent = 50;
  2040. } else {
  2041. $line->total_ht = 100;
  2042. $line->total_ttc = 119.6;
  2043. $line->total_tva = 19.6;
  2044. $line->remise_percent = 00;
  2045. }
  2046. if ($num_prods > 0) {
  2047. $prodid = mt_rand(1, $num_prods);
  2048. $line->fk_product = $prodids[$prodid];
  2049. }
  2050. $this->lines[$xnbp] = $line;
  2051. $this->total_ht += $line->total_ht;
  2052. $this->total_tva += $line->total_tva;
  2053. $this->total_ttc += $line->total_ttc;
  2054. $xnbp++;
  2055. }
  2056. }
  2057. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2058. /**
  2059. * Load indicator this->nb of global stats widget
  2060. *
  2061. * @return int <0 if ko, >0 if ok
  2062. */
  2063. public function load_state_board()
  2064. {
  2065. // phpcs:enable
  2066. global $conf, $user;
  2067. $this->nb = array();
  2068. $clause = "WHERE";
  2069. $sql = "SELECT count(p.rowid) as nb";
  2070. $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p";
  2071. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
  2072. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  2073. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  2074. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  2075. $clause = "AND";
  2076. }
  2077. $sql .= " ".$clause." p.entity IN (".getEntity('supplier_proposal').")";
  2078. $resql = $this->db->query($sql);
  2079. if ($resql) {
  2080. // This assignment in condition is not a bug. It allows walking the results.
  2081. while ($obj = $this->db->fetch_object($resql)) {
  2082. $this->nb["supplier_proposals"] = $obj->nb;
  2083. }
  2084. $this->db->free($resql);
  2085. return 1;
  2086. } else {
  2087. dol_print_error($this->db);
  2088. $this->error = $this->db->lasterror();
  2089. return -1;
  2090. }
  2091. }
  2092. /**
  2093. * Returns the reference to the following non used Proposal used depending on the active numbering module
  2094. * defined into SUPPLIER_PROPOSAL_ADDON
  2095. *
  2096. * @param Societe $soc Object thirdparty
  2097. * @return string Reference libre pour la propale
  2098. */
  2099. public function getNextNumRef($soc)
  2100. {
  2101. global $conf, $db, $langs;
  2102. $langs->load("supplier_proposal");
  2103. if (getDolGlobalString('SUPPLIER_PROPOSAL_ADDON')) {
  2104. $mybool = false;
  2105. $file = getDolGlobalString('SUPPLIER_PROPOSAL_ADDON') . ".php";
  2106. $classname = $conf->global->SUPPLIER_PROPOSAL_ADDON;
  2107. // Include file with class
  2108. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2109. foreach ($dirmodels as $reldir) {
  2110. $dir = dol_buildpath($reldir."core/modules/supplier_proposal/");
  2111. // Load file with numbering class (if found)
  2112. $mybool |= @include_once $dir.$file;
  2113. }
  2114. if (!$mybool) {
  2115. dol_print_error('', "Failed to include file ".$file);
  2116. return '';
  2117. }
  2118. $obj = new $classname();
  2119. $numref = "";
  2120. $numref = $obj->getNextValue($soc, $this);
  2121. if ($numref != "") {
  2122. return $numref;
  2123. } else {
  2124. $this->error = $obj->error;
  2125. return "";
  2126. }
  2127. } else {
  2128. $langs->load("errors");
  2129. print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("SupplierProposal"));
  2130. return "";
  2131. }
  2132. }
  2133. /**
  2134. * getTooltipContentArray
  2135. *
  2136. * @param array $params ex option, infologin
  2137. * @since v18
  2138. * @return array
  2139. */
  2140. public function getTooltipContentArray($params)
  2141. {
  2142. global $conf, $langs, $menumanager;
  2143. $langs->load('supplier_proposal');
  2144. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  2145. return ['optimize' => $langs->trans("ShowSupplierProposal")];
  2146. }
  2147. $option = $params['option'] ?? '';
  2148. $datas = [];
  2149. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("SupplierProposal").'</u>';
  2150. if (isset($this->status)) {
  2151. $datas['picto'] .= ' '.$this->getLibStatut(5);
  2152. }
  2153. if (!empty($this->ref)) {
  2154. $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  2155. }
  2156. if (!empty($this->ref_fourn)) {
  2157. $datas['ref_supplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_fourn;
  2158. }
  2159. if (!empty($this->total_ht)) {
  2160. $datas['amount_ht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  2161. }
  2162. if (!empty($this->total_tva)) {
  2163. $datas['amount_vat'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  2164. }
  2165. if (!empty($this->total_ttc)) {
  2166. $datas['amount_ttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  2167. }
  2168. return $datas;
  2169. }
  2170. /**
  2171. * Return clicable link of object (with eventually picto)
  2172. *
  2173. * @param int $withpicto Add picto into link
  2174. * @param string $option Where point the link ('compta', 'expedition', 'document', ...)
  2175. * @param string $get_params Parametres added to url
  2176. * @param int $notooltip 1=Disable tooltip
  2177. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  2178. * @param int $addlinktonotes Add link to show notes
  2179. * @return string String with URL
  2180. */
  2181. public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
  2182. {
  2183. global $langs, $conf, $user, $hookmanager;
  2184. if (!empty($conf->dol_no_mouse_hover)) {
  2185. $notooltip = 1; // Force disable tooltips
  2186. }
  2187. $url = '';
  2188. $result = '';
  2189. $params = [
  2190. 'id' => $this->id,
  2191. 'objecttype' => $this->element,
  2192. 'option' => $option,
  2193. ];
  2194. $classfortooltip = 'classfortooltip';
  2195. $dataparams = '';
  2196. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  2197. $classfortooltip = 'classforajaxtooltip';
  2198. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  2199. $label = '';
  2200. } else {
  2201. $label = implode($this->getTooltipContentArray($params));
  2202. }
  2203. if ($option == '') {
  2204. $url = DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$this->id.$get_params;
  2205. }
  2206. if ($option == 'document') {
  2207. $url = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$this->id.$get_params;
  2208. }
  2209. if ($option !== 'nolink') {
  2210. // Add param to save lastsearch_values or not
  2211. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  2212. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  2213. $add_save_lastsearch_values = 1;
  2214. }
  2215. if ($add_save_lastsearch_values) {
  2216. $url .= '&save_lastsearch_values=1';
  2217. }
  2218. }
  2219. $linkclose = '';
  2220. if (empty($notooltip) && $user->hasRight('propal', 'lire')) {
  2221. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  2222. $label = $langs->trans("ShowSupplierProposal");
  2223. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  2224. }
  2225. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  2226. $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
  2227. }
  2228. $linkstart = '<a href="'.$url.'"';
  2229. $linkstart .= $linkclose.'>';
  2230. $linkend = '</a>';
  2231. $result .= $linkstart;
  2232. if ($withpicto) {
  2233. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
  2234. }
  2235. if ($withpicto != 2) {
  2236. $result .= $this->ref;
  2237. }
  2238. $result .= $linkend;
  2239. if ($addlinktonotes) {
  2240. $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
  2241. if ($txttoshow) {
  2242. $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
  2243. $result .= ' <span class="note inline-block">';
  2244. $result .= '<a href="'.DOL_URL_ROOT.'/supplier_proposal/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
  2245. $result .= img_picto('', 'note');
  2246. $result .= '</a>';
  2247. //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
  2248. //$result.='</a>';
  2249. $result .= '</span>';
  2250. }
  2251. }
  2252. global $action;
  2253. $hookmanager->initHooks(array($this->element . 'dao'));
  2254. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  2255. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2256. if ($reshook > 0) {
  2257. $result = $hookmanager->resPrint;
  2258. } else {
  2259. $result .= $hookmanager->resPrint;
  2260. }
  2261. return $result;
  2262. }
  2263. /**
  2264. * Retrieve an array of supplier proposal lines
  2265. *
  2266. * @return int >0 if OK, <0 if KO
  2267. */
  2268. public function getLinesArray()
  2269. {
  2270. // For other object, here we call fetch_lines. But fetch_lines does not exists on supplier proposal
  2271. $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,';
  2272. $sql .= ' pt.qty, pt.tva_tx, pt.vat_src_code, pt.remise_percent, pt.subprice, pt.info_bits,';
  2273. $sql .= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,';
  2274. $sql .= ' pt.product_type, pt.rang, pt.fk_parent_line,';
  2275. $sql .= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,';
  2276. $sql .= ' p.description as product_desc, pt.ref_fourn as ref_supplier,';
  2277. $sql .= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc, pt.fk_unit';
  2278. $sql .= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pt';
  2279. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid';
  2280. $sql .= ' WHERE pt.fk_supplier_proposal = '.((int) $this->id);
  2281. $sql .= ' ORDER BY pt.rang ASC, pt.rowid';
  2282. dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG);
  2283. $resql = $this->db->query($sql);
  2284. if ($resql) {
  2285. $num = $this->db->num_rows($resql);
  2286. $i = 0;
  2287. while ($i < $num) {
  2288. $obj = $this->db->fetch_object($resql);
  2289. $this->lines[$i] = new SupplierProposalLine($this->db);
  2290. $this->lines[$i]->id = $obj->rowid; // for backward compatibility
  2291. $this->lines[$i]->rowid = $obj->rowid;
  2292. $this->lines[$i]->label = $obj->custom_label;
  2293. $this->lines[$i]->description = $obj->description;
  2294. $this->lines[$i]->fk_product = $obj->fk_product;
  2295. $this->lines[$i]->ref = $obj->ref;
  2296. $this->lines[$i]->product_label = $obj->product_label;
  2297. $this->lines[$i]->product_desc = $obj->product_desc;
  2298. $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated
  2299. $this->lines[$i]->product_type = $obj->product_type;
  2300. $this->lines[$i]->qty = $obj->qty;
  2301. $this->lines[$i]->subprice = $obj->subprice;
  2302. $this->lines[$i]->fk_remise_except = $obj->fk_remise_except;
  2303. $this->lines[$i]->remise_percent = $obj->remise_percent;
  2304. $this->lines[$i]->tva_tx = $obj->tva_tx;
  2305. $this->lines[$i]->vat_src_code = $obj->vat_src_code;
  2306. $this->lines[$i]->info_bits = $obj->info_bits;
  2307. $this->lines[$i]->total_ht = $obj->total_ht;
  2308. $this->lines[$i]->total_tva = $obj->total_tva;
  2309. $this->lines[$i]->total_ttc = $obj->total_ttc;
  2310. $this->lines[$i]->fk_fournprice = $obj->fk_fournprice;
  2311. $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht);
  2312. $this->lines[$i]->pa_ht = $marginInfos[0];
  2313. $this->lines[$i]->marge_tx = $marginInfos[1];
  2314. $this->lines[$i]->marque_tx = $marginInfos[2];
  2315. $this->lines[$i]->fk_parent_line = $obj->fk_parent_line;
  2316. $this->lines[$i]->special_code = $obj->special_code;
  2317. $this->lines[$i]->rang = $obj->rang;
  2318. $this->lines[$i]->ref_fourn = $obj->ref_supplier; // deprecated
  2319. $this->lines[$i]->ref_supplier = $obj->ref_supplier;
  2320. // Multicurrency
  2321. $this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency;
  2322. $this->lines[$i]->multicurrency_code = $obj->multicurrency_code;
  2323. $this->lines[$i]->multicurrency_subprice = $obj->multicurrency_subprice;
  2324. $this->lines[$i]->multicurrency_total_ht = $obj->multicurrency_total_ht;
  2325. $this->lines[$i]->multicurrency_total_tva = $obj->multicurrency_total_tva;
  2326. $this->lines[$i]->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  2327. $this->lines[$i]->fk_unit = $obj->fk_unit;
  2328. $i++;
  2329. }
  2330. $this->db->free($resql);
  2331. return 1;
  2332. } else {
  2333. $this->error = $this->db->error();
  2334. return -1;
  2335. }
  2336. }
  2337. /**
  2338. * Create a document onto disk according to template module.
  2339. *
  2340. * @param string $modele Force model to use ('' to not force)
  2341. * @param Translate $outputlangs Object langs to use for output
  2342. * @param int $hidedetails Hide details of lines
  2343. * @param int $hidedesc Hide description
  2344. * @param int $hideref Hide ref
  2345. * @param null|array $moreparams Array to provide more information
  2346. * @return int 0 if KO, 1 if OK
  2347. */
  2348. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  2349. {
  2350. global $conf, $langs;
  2351. $langs->load("supplier_proposal");
  2352. $outputlangs->load("products");
  2353. if (!dol_strlen($modele)) {
  2354. $modele = 'aurore';
  2355. if ($this->model_pdf) {
  2356. $modele = $this->model_pdf;
  2357. } elseif (getDolGlobalString('SUPPLIER_PROPOSAL_ADDON_PDF')) {
  2358. $modele = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF;
  2359. }
  2360. }
  2361. $modelpath = "core/modules/supplier_proposal/doc/";
  2362. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  2363. }
  2364. /**
  2365. * Function used to replace a thirdparty id with another one.
  2366. *
  2367. * @param DoliDB $dbs Database handler, because function is static we name it $dbs not $db to avoid breaking coding test
  2368. * @param int $origin_id Old thirdparty id
  2369. * @param int $dest_id New thirdparty id
  2370. * @return bool
  2371. */
  2372. public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
  2373. {
  2374. $tables = array(
  2375. 'supplier_proposal'
  2376. );
  2377. return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
  2378. }
  2379. /**
  2380. * Function used to replace a product id with another one.
  2381. *
  2382. * @param DoliDB $db Database handler
  2383. * @param int $origin_id Old product id
  2384. * @param int $dest_id New product id
  2385. * @return bool
  2386. */
  2387. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  2388. {
  2389. $tables = array(
  2390. 'supplier_proposaldet'
  2391. );
  2392. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  2393. }
  2394. /**
  2395. * Return clicable link of object (with eventually picto)
  2396. *
  2397. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  2398. * @param array $arraydata Array of data
  2399. * @return string HTML Code for Kanban thumb.
  2400. */
  2401. public function getKanbanView($option = '', $arraydata = null)
  2402. {
  2403. global $langs;
  2404. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  2405. $return = '<div class="box-flex-item box-flex-grow-zero">';
  2406. $return .= '<div class="info-box info-box-sm">';
  2407. $return .= '<span class="info-box-icon bg-infobox-action">';
  2408. $return .= img_picto('', $this->picto);
  2409. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  2410. $return .= '</span>';
  2411. $return .= '<div class="info-box-content">';
  2412. $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  2413. if ($selected >= 0) {
  2414. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  2415. }
  2416. if (property_exists($this, 'socid')) {
  2417. $return .= '<span class="info-box-ref"> | '.$this->socid.'</span>';
  2418. }
  2419. if (property_exists($this, 'delivery_date')) {
  2420. $return .= '<br><span class="opacitymedium">'.$langs->trans("DateEnd").'</span> : <span class="info-box-label">'.dol_print_date($this->delivery_date).'</span>';
  2421. }
  2422. if (property_exists($this, 'total_ttc')) {
  2423. $return .='<br><span class="opacitymedium" >'.$langs->trans("AmountHT").' : </span><span class="info-box-label amount">'.price($this->total_ttc).'</span>';
  2424. }
  2425. if (method_exists($this, 'getLibStatut')) {
  2426. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
  2427. }
  2428. $return .= '</div>';
  2429. $return .= '</div>';
  2430. $return .= '</div>';
  2431. return $return;
  2432. }
  2433. }
  2434. /**
  2435. * Class to manage supplier_proposal lines
  2436. */
  2437. class SupplierProposalLine extends CommonObjectLine
  2438. {
  2439. /**
  2440. * @var DoliDB Database handler.
  2441. */
  2442. public $db;
  2443. /**
  2444. * @var string Error code (or message)
  2445. */
  2446. public $error = '';
  2447. /**
  2448. * @var string ID to identify managed object
  2449. */
  2450. public $element = 'supplier_proposaldet';
  2451. /**
  2452. * @var string Name of table without prefix where object is stored
  2453. */
  2454. public $table_element = 'supplier_proposaldet';
  2455. public $oldline;
  2456. /**
  2457. * @var int ID
  2458. */
  2459. public $id;
  2460. /**
  2461. * @var int ID
  2462. */
  2463. public $fk_supplier_proposal;
  2464. /**
  2465. * @var int ID
  2466. */
  2467. public $fk_parent_line;
  2468. public $desc; // Description ligne
  2469. /**
  2470. * @var int ID
  2471. */
  2472. public $fk_product; // Id produit predefini
  2473. /**
  2474. * @deprecated
  2475. * @see $product_type
  2476. */
  2477. public $fk_product_type;
  2478. /**
  2479. * Product type
  2480. * @var int
  2481. * @see Product::TYPE_PRODUCT, Product::TYPE_SERVICE
  2482. */
  2483. public $product_type = Product::TYPE_PRODUCT;
  2484. public $qty;
  2485. public $tva_tx;
  2486. public $vat_src_code;
  2487. public $subprice;
  2488. public $remise_percent;
  2489. /**
  2490. * @var int ID
  2491. */
  2492. public $fk_remise_except;
  2493. public $rang = 0;
  2494. /**
  2495. * @var int ID
  2496. */
  2497. public $fk_fournprice;
  2498. public $pa_ht;
  2499. public $marge_tx;
  2500. public $marque_tx;
  2501. public $special_code; // Tag for special lines (exlusive tags)
  2502. // 1: frais de port
  2503. // 2: ecotaxe
  2504. // 3: option line (when qty = 0)
  2505. public $info_bits = 0; // Liste d'options cumulables:
  2506. // Bit 0: 0 si TVA normal - 1 si TVA NPR
  2507. // Bit 1: 0 ligne normale - 1 si ligne de remise fixe
  2508. public $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne
  2509. public $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne
  2510. public $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne
  2511. public $date_start;
  2512. public $date_end;
  2513. // From llx_product
  2514. /**
  2515. * @deprecated
  2516. * @see $product_ref
  2517. */
  2518. public $ref;
  2519. /**
  2520. * Product reference
  2521. * @var string
  2522. */
  2523. public $product_ref;
  2524. /**
  2525. * @deprecated
  2526. * @see $product_label
  2527. */
  2528. public $libelle;
  2529. /**
  2530. * Product label
  2531. * @var string
  2532. */
  2533. public $product_label;
  2534. /**
  2535. * Custom label
  2536. * @var string
  2537. */
  2538. public $label;
  2539. /**
  2540. * Product description
  2541. * @var string
  2542. */
  2543. public $product_desc;
  2544. public $localtax1_tx; // Local tax 1
  2545. public $localtax2_tx; // Local tax 2
  2546. public $localtax1_type; // Local tax 1 type
  2547. public $localtax2_type; // Local tax 2 type
  2548. public $total_localtax1; // Line total local tax 1
  2549. public $total_localtax2; // Line total local tax 2
  2550. public $skip_update_total; // Skip update price total for special lines
  2551. public $ref_fourn;
  2552. public $ref_supplier;
  2553. // Multicurrency
  2554. /**
  2555. * @var int ID
  2556. */
  2557. public $fk_multicurrency;
  2558. public $multicurrency_code;
  2559. public $multicurrency_subprice;
  2560. public $multicurrency_total_ht;
  2561. public $multicurrency_total_tva;
  2562. public $multicurrency_total_ttc;
  2563. /**
  2564. * Class line Contructor
  2565. *
  2566. * @param DoliDB $db Database handler
  2567. */
  2568. public function __construct($db)
  2569. {
  2570. $this->db = $db;
  2571. }
  2572. /**
  2573. * Retrieve the propal line object
  2574. *
  2575. * @param int $rowid Propal line id
  2576. * @return int <0 if KO, >0 if OK
  2577. */
  2578. public function fetch($rowid)
  2579. {
  2580. $sql = 'SELECT pd.rowid, pd.fk_supplier_proposal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.tva_tx,';
  2581. $sql .= ' pd.date_start, pd.date_end,';
  2582. $sql .= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,';
  2583. $sql .= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,';
  2584. $sql .= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,';
  2585. $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,';
  2586. $sql .= ' pd.product_type, pd.ref_fourn as ref_produit_fourn,';
  2587. $sql .= ' pd.fk_multicurrency, pd.multicurrency_code, pd.multicurrency_subprice, pd.multicurrency_total_ht, pd.multicurrency_total_tva, pd.multicurrency_total_ttc, pd.fk_unit';
  2588. $sql .= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pd';
  2589. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid';
  2590. $sql .= ' WHERE pd.rowid = '.((int) $rowid);
  2591. $result = $this->db->query($sql);
  2592. if ($result) {
  2593. $objp = $this->db->fetch_object($result);
  2594. $this->id = $objp->rowid;
  2595. $this->fk_supplier_proposal = $objp->fk_supplier_proposal;
  2596. $this->fk_parent_line = $objp->fk_parent_line;
  2597. $this->label = $objp->custom_label;
  2598. $this->desc = $objp->description;
  2599. $this->qty = $objp->qty;
  2600. $this->subprice = $objp->subprice;
  2601. $this->tva_tx = $objp->tva_tx;
  2602. $this->remise_percent = $objp->remise_percent;
  2603. $this->fk_remise_except = $objp->fk_remise_except;
  2604. $this->fk_product = $objp->fk_product;
  2605. $this->info_bits = $objp->info_bits;
  2606. $this->date_start = $this->db->jdate($objp->date_start);
  2607. $this->date_end = $this->db->jdate($objp->date_end);
  2608. $this->total_ht = $objp->total_ht;
  2609. $this->total_tva = $objp->total_tva;
  2610. $this->total_ttc = $objp->total_ttc;
  2611. $this->fk_fournprice = $objp->fk_fournprice;
  2612. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
  2613. $this->pa_ht = $marginInfos[0];
  2614. $this->marge_tx = $marginInfos[1];
  2615. $this->marque_tx = $marginInfos[2];
  2616. $this->special_code = $objp->special_code;
  2617. $this->product_type = $objp->product_type;
  2618. $this->rang = $objp->rang;
  2619. $this->ref = $objp->product_ref; // deprecated
  2620. $this->product_ref = $objp->product_ref;
  2621. $this->libelle = $objp->product_label; // deprecated
  2622. $this->product_label = $objp->product_label;
  2623. $this->product_desc = $objp->product_desc;
  2624. $this->ref_fourn = $objp->ref_produit_fourn;
  2625. // Multicurrency
  2626. $this->fk_multicurrency = $objp->fk_multicurrency;
  2627. $this->multicurrency_code = $objp->multicurrency_code;
  2628. $this->multicurrency_subprice = $objp->multicurrency_subprice;
  2629. $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
  2630. $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
  2631. $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  2632. $this->fk_unit = $objp->fk_unit;
  2633. $this->db->free($result);
  2634. return 1;
  2635. } else {
  2636. dol_print_error($this->db);
  2637. return -1;
  2638. }
  2639. }
  2640. /**
  2641. * Insert object line propal in database
  2642. *
  2643. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2644. * @return int <0 if KO, >0 if OK
  2645. */
  2646. public function insert($notrigger = 0)
  2647. {
  2648. global $conf, $langs, $user;
  2649. $error = 0;
  2650. dol_syslog(get_class($this)."::insert rang=".$this->rang);
  2651. // Clean parameters
  2652. if (empty($this->tva_tx)) {
  2653. $this->tva_tx = 0;
  2654. }
  2655. if (empty($this->vat_src_code)) {
  2656. $this->vat_src_code = '';
  2657. }
  2658. if (empty($this->localtax1_tx)) {
  2659. $this->localtax1_tx = 0;
  2660. }
  2661. if (empty($this->localtax2_tx)) {
  2662. $this->localtax2_tx = 0;
  2663. }
  2664. if (empty($this->localtax1_type)) {
  2665. $this->localtax1_type = 0;
  2666. }
  2667. if (empty($this->localtax2_type)) {
  2668. $this->localtax2_type = 0;
  2669. }
  2670. if (empty($this->total_localtax1)) {
  2671. $this->total_localtax1 = 0;
  2672. }
  2673. if (empty($this->total_localtax2)) {
  2674. $this->total_localtax2 = 0;
  2675. }
  2676. if (empty($this->rang)) {
  2677. $this->rang = 0;
  2678. }
  2679. if (empty($this->remise_percent)) {
  2680. $this->remise_percent = 0;
  2681. }
  2682. if (empty($this->info_bits)) {
  2683. $this->info_bits = 0;
  2684. }
  2685. if (empty($this->special_code)) {
  2686. $this->special_code = 0;
  2687. }
  2688. if (empty($this->fk_parent_line)) {
  2689. $this->fk_parent_line = 0;
  2690. }
  2691. if (empty($this->fk_fournprice)) {
  2692. $this->fk_fournprice = 0;
  2693. }
  2694. if (empty($this->fk_unit)) {
  2695. $this->fk_unit = 0;
  2696. }
  2697. if (empty($this->subprice)) {
  2698. $this->subprice = 0;
  2699. }
  2700. if (empty($this->pa_ht)) {
  2701. $this->pa_ht = 0;
  2702. }
  2703. // if buy price not defined, define buyprice as configured in margin admin
  2704. if ($this->pa_ht == 0) {
  2705. $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
  2706. if ($result < 0) {
  2707. return $result;
  2708. } else {
  2709. $this->pa_ht = $result;
  2710. }
  2711. }
  2712. // Check parameters
  2713. if ($this->product_type < 0) {
  2714. return -1;
  2715. }
  2716. $this->db->begin();
  2717. // Insert line into database
  2718. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'supplier_proposaldet';
  2719. $sql .= ' (fk_supplier_proposal, fk_parent_line, label, description, fk_product, product_type,';
  2720. $sql .= ' date_start, date_end,';
  2721. $sql .= ' fk_remise_except, qty, tva_tx, vat_src_code, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
  2722. $sql .= ' subprice, remise_percent, ';
  2723. $sql .= ' info_bits, ';
  2724. $sql .= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,';
  2725. $sql .= ' ref_fourn,';
  2726. $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc, fk_unit)';
  2727. $sql .= " VALUES (".$this->fk_supplier_proposal.",";
  2728. $sql .= " ".($this->fk_parent_line > 0 ? ((int) $this->fk_parent_line) : "null").",";
  2729. $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
  2730. $sql .= " '".$this->db->escape($this->desc)."',";
  2731. $sql .= " ".($this->fk_product ? ((int) $this->fk_product) : "null").",";
  2732. $sql .= " '".$this->db->escape($this->product_type)."',";
  2733. $sql .= " ".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null").",";
  2734. $sql .= " ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null").",";
  2735. $sql .= " ".($this->fk_remise_except ? ((int) $this->fk_remise_except) : "null").",";
  2736. $sql .= " ".price2num($this->qty, 'MS').",";
  2737. $sql .= " ".price2num($this->tva_tx).",";
  2738. $sql .= " '".$this->db->escape($this->vat_src_code)."',";
  2739. $sql .= " ".price2num($this->localtax1_tx).",";
  2740. $sql .= " ".price2num($this->localtax2_tx).",";
  2741. $sql .= " '".$this->db->escape($this->localtax1_type)."',";
  2742. $sql .= " '".$this->db->escape($this->localtax2_type)."',";
  2743. $sql .= " ".price2num($this->subprice, 'MU') .",";
  2744. $sql .= " ".((float) $this->remise_percent).",";
  2745. $sql .= " ".(isset($this->info_bits) ? ((int) $this->info_bits) : "null").",";
  2746. $sql .= " ".price2num($this->total_ht, 'MT').",";
  2747. $sql .= " ".price2num($this->total_tva, 'MT').",";
  2748. $sql .= " ".price2num($this->total_localtax1, 'MT').",";
  2749. $sql .= " ".price2num($this->total_localtax2, 'MT').",";
  2750. $sql .= " ".price2num($this->total_ttc, 'MT').",";
  2751. $sql .= " ".(!empty($this->fk_fournprice) ? ((int) $this->fk_fournprice) : "null").",";
  2752. $sql .= " ".(isset($this->pa_ht) ? price2num($this->pa_ht, 'MU') : "null").",";
  2753. $sql .= ' '.((int) $this->special_code).',';
  2754. $sql .= ' '.((int) $this->rang).',';
  2755. $sql .= " '".$this->db->escape($this->ref_fourn)."'";
  2756. $sql .= ", ".($this->fk_multicurrency > 0 ? ((int) $this->fk_multicurrency) : 'null');
  2757. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  2758. $sql .= ", ".price2num($this->multicurrency_subprice, 'CU');
  2759. $sql .= ", ".price2num($this->multicurrency_total_ht, 'CT');
  2760. $sql .= ", ".price2num($this->multicurrency_total_tva, 'CT');
  2761. $sql .= ", ".price2num($this->multicurrency_total_ttc, 'CT');
  2762. $sql .= ", ".($this->fk_unit ? ((int) $this->fk_unit) : 'null');
  2763. $sql .= ')';
  2764. dol_syslog(get_class($this).'::insert', LOG_DEBUG);
  2765. $resql = $this->db->query($sql);
  2766. if ($resql) {
  2767. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'supplier_proposaldet');
  2768. if (!$error) {
  2769. $result = $this->insertExtraFields();
  2770. if ($result < 0) {
  2771. $error++;
  2772. }
  2773. }
  2774. if (!$error && !$notrigger) {
  2775. // Call trigger
  2776. $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_INSERT', $user);
  2777. if ($result < 0) {
  2778. $this->db->rollback();
  2779. return -1;
  2780. }
  2781. // End call triggers
  2782. }
  2783. $this->db->commit();
  2784. return 1;
  2785. } else {
  2786. $this->error = $this->db->error()." sql=".$sql;
  2787. $this->db->rollback();
  2788. return -1;
  2789. }
  2790. }
  2791. /**
  2792. * Delete line in database
  2793. *
  2794. * @return int <0 if ko, >0 if ok
  2795. */
  2796. public function delete()
  2797. {
  2798. global $conf, $langs, $user;
  2799. $error = 0;
  2800. $this->db->begin();
  2801. $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE rowid = ".((int) $this->id);
  2802. dol_syslog("SupplierProposalLine::delete", LOG_DEBUG);
  2803. if ($this->db->query($sql)) {
  2804. // Remove extrafields
  2805. if (!$error) {
  2806. $result = $this->deleteExtraFields();
  2807. if ($result < 0) {
  2808. $error++;
  2809. dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
  2810. }
  2811. }
  2812. // Call trigger
  2813. $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_DELETE', $user);
  2814. if ($result < 0) {
  2815. $this->db->rollback();
  2816. return -1;
  2817. }
  2818. // End call triggers
  2819. $this->db->commit();
  2820. return 1;
  2821. } else {
  2822. $this->error = $this->db->error()." sql=".$sql;
  2823. $this->db->rollback();
  2824. return -1;
  2825. }
  2826. }
  2827. /**
  2828. * Update propal line object into DB
  2829. *
  2830. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2831. * @return int <0 if ko, >0 if ok
  2832. */
  2833. public function update($notrigger = 0)
  2834. {
  2835. global $conf, $langs, $user;
  2836. $error = 0;
  2837. // Clean parameters
  2838. if (empty($this->tva_tx)) {
  2839. $this->tva_tx = 0;
  2840. }
  2841. if (empty($this->localtax1_tx)) {
  2842. $this->localtax1_tx = 0;
  2843. }
  2844. if (empty($this->localtax2_tx)) {
  2845. $this->localtax2_tx = 0;
  2846. }
  2847. if (empty($this->total_localtax1)) {
  2848. $this->total_localtax1 = 0;
  2849. }
  2850. if (empty($this->total_localtax2)) {
  2851. $this->total_localtax2 = 0;
  2852. }
  2853. if (empty($this->localtax1_type)) {
  2854. $this->localtax1_type = 0;
  2855. }
  2856. if (empty($this->localtax2_type)) {
  2857. $this->localtax2_type = 0;
  2858. }
  2859. if (empty($this->marque_tx)) {
  2860. $this->marque_tx = 0;
  2861. }
  2862. if (empty($this->marge_tx)) {
  2863. $this->marge_tx = 0;
  2864. }
  2865. if (empty($this->remise_percent)) {
  2866. $this->remise_percent = 0;
  2867. }
  2868. if (empty($this->info_bits)) {
  2869. $this->info_bits = 0;
  2870. }
  2871. if (empty($this->special_code)) {
  2872. $this->special_code = 0;
  2873. }
  2874. if (empty($this->fk_parent_line)) {
  2875. $this->fk_parent_line = 0;
  2876. }
  2877. if (empty($this->fk_fournprice)) {
  2878. $this->fk_fournprice = 0;
  2879. }
  2880. if (empty($this->fk_unit)) {
  2881. $this->fk_unit = 0;
  2882. }
  2883. if (empty($this->subprice)) {
  2884. $this->subprice = 0;
  2885. }
  2886. if (empty($this->pa_ht)) {
  2887. $this->pa_ht = 0;
  2888. }
  2889. // if buy price not defined, define buyprice as configured in margin admin
  2890. if ($this->pa_ht == 0) {
  2891. $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
  2892. if ($result < 0) {
  2893. return $result;
  2894. } else {
  2895. $this->pa_ht = $result;
  2896. }
  2897. }
  2898. $this->db->begin();
  2899. // Mise a jour ligne en base
  2900. $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposaldet SET";
  2901. $sql .= " description='".$this->db->escape($this->desc)."'";
  2902. $sql .= " , label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
  2903. $sql .= " , product_type=".((int) $this->product_type);
  2904. $sql .= " , date_start=".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null");
  2905. $sql .= " , date_end=".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null");
  2906. $sql .= " , tva_tx='".price2num($this->tva_tx)."'";
  2907. $sql .= " , localtax1_tx=".price2num($this->localtax1_tx);
  2908. $sql .= " , localtax2_tx=".price2num($this->localtax2_tx);
  2909. $sql .= " , localtax1_type='".$this->db->escape($this->localtax1_type)."'";
  2910. $sql .= " , localtax2_type='".$this->db->escape($this->localtax2_type)."'";
  2911. $sql .= " , qty='".price2num($this->qty)."'";
  2912. $sql .= " , subprice=".price2num($this->subprice);
  2913. $sql .= " , remise_percent=".price2num($this->remise_percent);
  2914. $sql .= " , info_bits='".$this->db->escape($this->info_bits)."'";
  2915. if (empty($this->skip_update_total)) {
  2916. $sql .= " , total_ht=".price2num($this->total_ht);
  2917. $sql .= " , total_tva=".price2num($this->total_tva);
  2918. $sql .= " , total_ttc=".price2num($this->total_ttc);
  2919. $sql .= " , total_localtax1=".price2num($this->total_localtax1);
  2920. $sql .= " , total_localtax2=".price2num($this->total_localtax2);
  2921. }
  2922. $sql .= " , fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
  2923. $sql .= " , buy_price_ht=".price2num($this->pa_ht);
  2924. if (strlen($this->special_code)) {
  2925. $sql .= " , special_code=".((int) $this->special_code);
  2926. }
  2927. $sql .= " , fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
  2928. if (!empty($this->rang)) {
  2929. $sql .= ", rang=".((int) $this->rang);
  2930. }
  2931. $sql .= " , ref_fourn=".(!empty($this->ref_fourn) ? "'".$this->db->escape($this->ref_fourn)."'" : "null");
  2932. $sql .= " , fk_unit=".($this->fk_unit ? $this->fk_unit : 'null');
  2933. // Multicurrency
  2934. $sql .= " , multicurrency_subprice=".price2num($this->multicurrency_subprice);
  2935. $sql .= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
  2936. $sql .= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
  2937. $sql .= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
  2938. $sql .= " WHERE rowid = ".((int) $this->id);
  2939. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  2940. $resql = $this->db->query($sql);
  2941. if ($resql) {
  2942. if (!$error) {
  2943. $result = $this->insertExtraFields();
  2944. if ($result < 0) {
  2945. $error++;
  2946. }
  2947. }
  2948. if (!$error && !$notrigger) {
  2949. // Call trigger
  2950. $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_MODIFY', $user);
  2951. if ($result < 0) {
  2952. $this->db->rollback();
  2953. return -1;
  2954. }
  2955. // End call triggers
  2956. }
  2957. $this->db->commit();
  2958. return 1;
  2959. } else {
  2960. $this->error = $this->db->error();
  2961. $this->db->rollback();
  2962. return -2;
  2963. }
  2964. }
  2965. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2966. /**
  2967. * Update DB line fields total_xxx
  2968. * Used by migration
  2969. *
  2970. * @return int <0 if ko, >0 if ok
  2971. */
  2972. public function update_total()
  2973. {
  2974. // phpcs:enable
  2975. $this->db->begin();
  2976. // Mise a jour ligne en base
  2977. $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposaldet SET";
  2978. $sql .= " total_ht=".price2num($this->total_ht, 'MT');
  2979. $sql .= ",total_tva=".price2num($this->total_tva, 'MT');
  2980. $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT');
  2981. $sql .= " WHERE rowid = ".((int) $this->id);
  2982. dol_syslog("SupplierProposalLine::update_total", LOG_DEBUG);
  2983. $resql = $this->db->query($sql);
  2984. if ($resql) {
  2985. $this->db->commit();
  2986. return 1;
  2987. } else {
  2988. $this->error = $this->db->error();
  2989. $this->db->rollback();
  2990. return -2;
  2991. }
  2992. }
  2993. }