supplier_proposal.class.php 111 KB

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