propal.class.php 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544
  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-2022 Philippe Grand <philippe.grand@atoo-net.com>
  11. * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
  12. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  13. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  16. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
  18. * Copyright (C) 2022 ATM Consulting <contact@atm-consulting.fr>
  19. * Copyright (C) 2022 OpenDSI <support@open-dsi.fr>
  20. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  21. *
  22. * This program is free software; you can redistribute it and/or modify
  23. * it under the terms of the GNU General Public License as published by
  24. * the Free Software Foundation; either version 3 of the License, or
  25. * (at your option) any later version.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU General Public License
  33. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  34. */
  35. /**
  36. * \file htdocs/comm/propal/class/propal.class.php
  37. * \brief File of class to manage proposals
  38. */
  39. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  40. require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
  41. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  43. require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
  44. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  45. require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
  46. /**
  47. * Class to manage proposals
  48. */
  49. class Propal extends CommonObject
  50. {
  51. use CommonIncoterm;
  52. /**
  53. * @var string code
  54. */
  55. public $code = "";
  56. /**
  57. * @var string ID to identify managed object
  58. */
  59. public $element = 'propal';
  60. /**
  61. * @var string Name of table without prefix where object is stored
  62. */
  63. public $table_element = 'propal';
  64. /**
  65. * @var int Name of subtable line
  66. */
  67. public $table_element_line = 'propaldet';
  68. /**
  69. * @var string Fieldname with ID of parent key if this field has a parent
  70. */
  71. public $fk_element = 'fk_propal';
  72. /**
  73. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  74. */
  75. public $picto = 'propal';
  76. /**
  77. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  78. * @var int
  79. */
  80. public $ismultientitymanaged = 1;
  81. /**
  82. * 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
  83. * @var integer
  84. */
  85. public $restrictiononfksoc = 1;
  86. /**
  87. * {@inheritdoc}
  88. */
  89. protected $table_ref_field = 'ref';
  90. /**
  91. * ID of the client
  92. * @var int
  93. */
  94. public $socid;
  95. /**
  96. * ID of the contact
  97. * @var int
  98. */
  99. public $contactid;
  100. public $author;
  101. /**
  102. * Ref from thirdparty
  103. * @var string
  104. */
  105. public $ref_client;
  106. /**
  107. * Status of the quote
  108. * @var int
  109. * @see Propal::STATUS_DRAFT, Propal::STATUS_VALIDATED, Propal::STATUS_SIGNED, Propal::STATUS_NOTSIGNED, Propal::STATUS_BILLED
  110. */
  111. public $statut;
  112. /**
  113. * Status of the quote
  114. * @var int
  115. * @see Propal::STATUS_DRAFT, Propal::STATUS_VALIDATED, Propal::STATUS_SIGNED, Propal::STATUS_NOTSIGNED, Propal::STATUS_BILLED
  116. */
  117. public $status;
  118. /**
  119. * @deprecated
  120. * @see $date_creation
  121. */
  122. public $datec;
  123. /**
  124. * @var integer|string $date_creation;
  125. */
  126. public $date_creation;
  127. /**
  128. * @deprecated
  129. * @see $date_validation
  130. */
  131. public $datev;
  132. /**
  133. * @var integer|string $date_validation;
  134. */
  135. public $date_validation;
  136. /**
  137. * @var integer|string $date_signature;
  138. */
  139. public $date_signature;
  140. /**
  141. * @var User $user_signature
  142. */
  143. public $user_signature;
  144. /**
  145. * @var integer|string date of the quote;
  146. */
  147. public $date;
  148. /**
  149. * @deprecated
  150. * @see $date
  151. */
  152. public $datep;
  153. /**
  154. * @var int Date expected for delivery
  155. * @deprecated
  156. */
  157. public $date_livraison; // deprecated; Use delivery_date instead.
  158. /**
  159. * @var integer|string $delivery_date;
  160. */
  161. public $delivery_date; // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
  162. public $fin_validite;
  163. public $user_author_id;
  164. public $user_valid_id;
  165. public $user_close_id;
  166. /**
  167. * @deprecated
  168. * @see $total_ht
  169. */
  170. public $price;
  171. /**
  172. * @deprecated
  173. * @see $total_tva
  174. */
  175. public $tva;
  176. /**
  177. * @deprecated
  178. * @see $total_ttc
  179. */
  180. public $total;
  181. public $cond_reglement_code;
  182. public $deposit_percent;
  183. public $mode_reglement_code;
  184. public $remise_percent;
  185. /**
  186. * @deprecated
  187. */
  188. public $remise;
  189. /**
  190. * @deprecated
  191. */
  192. public $remise_absolue;
  193. /**
  194. * @var int ID
  195. * @deprecated
  196. */
  197. public $fk_address;
  198. public $address_type;
  199. public $address;
  200. public $availability_id;
  201. public $availability_code;
  202. public $duree_validite;
  203. public $demand_reason_id;
  204. public $demand_reason_code;
  205. public $warehouse_id;
  206. public $extraparams = array();
  207. /**
  208. * @var PropaleLigne[]
  209. */
  210. public $lines = array();
  211. public $line;
  212. public $labelStatus = array();
  213. public $labelStatusShort = array();
  214. // Multicurrency
  215. /**
  216. * @var int ID
  217. */
  218. public $fk_multicurrency;
  219. public $multicurrency_code;
  220. public $multicurrency_tx;
  221. public $multicurrency_total_ht;
  222. public $multicurrency_total_tva;
  223. public $multicurrency_total_ttc;
  224. /**
  225. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  226. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  227. * 'label' the translation key.
  228. * 'enabled' is a condition when the field must be managed.
  229. * 'position' is the sort order of field.
  230. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  231. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  232. * 'noteditable' says if field is not editable (1 or 0)
  233. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  234. * 'index' if we want an index in database.
  235. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  236. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  237. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  238. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  239. * 'help' is a string visible as a tooltip on field
  240. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  241. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  242. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  243. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  244. *
  245. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  246. */
  247. // BEGIN MODULEBUILDER PROPERTIES
  248. /**
  249. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  250. */
  251. public $fields = array(
  252. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  253. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>15, 'index'=>1),
  254. 'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>20),
  255. 'ref_client' =>array('type'=>'varchar(255)', 'label'=>'RefCustomer', 'enabled'=>1, 'visible'=>-1, 'position'=>22),
  256. 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>40),
  257. 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'$conf->societe->enabled', 'visible'=>-1, 'position'=>23),
  258. 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label'=>'Fk projet', 'enabled'=>"isModEnabled('project')", 'visible'=>-1, 'position'=>24),
  259. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
  260. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
  261. 'datep' =>array('type'=>'date', 'label'=>'Date', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
  262. 'fin_validite' =>array('type'=>'datetime', 'label'=>'DateEnd', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
  263. 'date_valid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
  264. 'date_cloture' =>array('type'=>'datetime', 'label'=>'DateClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
  265. 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
  266. 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>85),
  267. 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  268. 'fk_user_cloture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user cloture', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
  269. 'price' =>array('type'=>'double', 'label'=>'Price', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
  270. 'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
  271. //'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
  272. //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
  273. 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1),
  274. 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'VAT', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1),
  275. 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LocalTax1', 'enabled'=>1, 'visible'=>-1, 'position'=>135, 'isameasure'=>1),
  276. 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LocalTax2', 'enabled'=>1, 'visible'=>-1, 'position'=>140, 'isameasure'=>1),
  277. 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>145, 'isameasure'=>1),
  278. 'fk_account' =>array('type'=>'integer', 'label'=>'BankAccount', 'enabled'=>'$conf->banque->enabled', 'visible'=>-1, 'position'=>150),
  279. 'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>155),
  280. 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
  281. 'deposit_percent' =>array('type'=>'varchar(63)', 'label'=>'DepositPercent', 'enabled'=>1, 'visible'=>-1, 'position'=>161),
  282. 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
  283. 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>170),
  284. 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>175),
  285. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'PDFTemplate', 'enabled'=>1, 'visible'=>0, 'position'=>180),
  286. 'date_livraison' =>array('type'=>'date', 'label'=>'DateDeliveryPlanned', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
  287. 'fk_shipping_method' =>array('type'=>'integer', 'label'=>'ShippingMethod', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
  288. 'fk_warehouse' =>array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Fk warehouse', 'enabled'=>'$conf->stock->enabled', 'visible'=>-1, 'position'=>191),
  289. 'fk_availability' =>array('type'=>'integer', 'label'=>'Availability', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
  290. 'fk_delivery_address' =>array('type'=>'integer', 'label'=>'DeliveryAddress', 'enabled'=>1, 'visible'=>0, 'position'=>200), // deprecated
  291. 'fk_input_reason' =>array('type'=>'integer', 'label'=>'InputReason', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
  292. 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
  293. 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>220),
  294. 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>225),
  295. 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyID', 'enabled'=>1, 'visible'=>-1, 'position'=>230),
  296. 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCurrency', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>235),
  297. 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>240, 'isameasure'=>1),
  298. 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>245, 'isameasure'=>1),
  299. 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>250, 'isameasure'=>1),
  300. 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>255, 'isameasure'=>1),
  301. 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>260),
  302. 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
  303. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900),
  304. );
  305. // END MODULEBUILDER PROPERTIES
  306. /**
  307. * Draft status
  308. */
  309. const STATUS_DRAFT = 0;
  310. /**
  311. * Validated status
  312. */
  313. const STATUS_VALIDATED = 1;
  314. /**
  315. * Signed quote
  316. */
  317. const STATUS_SIGNED = 2;
  318. /**
  319. * Not signed quote
  320. */
  321. const STATUS_NOTSIGNED = 3;
  322. /**
  323. * Billed or processed quote
  324. */
  325. const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ?
  326. /**
  327. * Constructor
  328. *
  329. * @param DoliDB $db Database handler
  330. * @param int $socid Id third party
  331. * @param int $propalid Id proposal
  332. */
  333. public function __construct($db, $socid = 0, $propalid = 0)
  334. {
  335. global $conf, $langs;
  336. $this->db = $db;
  337. $this->socid = $socid;
  338. $this->id = $propalid;
  339. $this->duree_validite = getDolGlobalInt('PROPALE_VALIDITY_DURATION', 0);
  340. }
  341. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  342. /**
  343. * Add line into array ->lines
  344. * $this->thirdparty should be loaded
  345. *
  346. * @param int $idproduct Product Id to add
  347. * @param int $qty Quantity
  348. * @param int $remise_percent Discount effected on Product
  349. * @return int <0 if KO, >0 if OK
  350. *
  351. * TODO Replace calls to this function by generation objet Ligne
  352. */
  353. public function add_product($idproduct, $qty, $remise_percent = 0)
  354. {
  355. // phpcs:enable
  356. global $conf, $mysoc;
  357. if (!$qty) {
  358. $qty = 1;
  359. }
  360. dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent");
  361. if ($idproduct > 0) {
  362. $prod = new Product($this->db);
  363. $prod->fetch($idproduct);
  364. $productdesc = $prod->description;
  365. $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id);
  366. $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
  367. if (empty($tva_tx)) {
  368. $tva_npr = 0;
  369. }
  370. $vat_src_code = ''; // May be defined into tva_tx
  371. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr);
  372. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr);
  373. // multiprices
  374. if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) {
  375. $price = $prod->multiprices[$this->thirdparty->price_level];
  376. } else {
  377. $price = $prod->price;
  378. }
  379. $line = new PropaleLigne($this->db);
  380. $line->fk_product = $idproduct;
  381. $line->desc = $productdesc;
  382. $line->qty = $qty;
  383. $line->subprice = $price;
  384. $line->remise_percent = $remise_percent;
  385. $line->vat_src_code = $vat_src_code;
  386. $line->tva_tx = $tva_tx;
  387. $line->fk_unit = $prod->fk_unit;
  388. if ($tva_npr) {
  389. $line->info_bits = 1;
  390. }
  391. $this->lines[] = $line;
  392. }
  393. }
  394. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  395. /**
  396. * Adding line of fixed discount in the proposal in DB
  397. *
  398. * @param int $idremise Id of fixed discount
  399. * @return int >0 if OK, <0 if KO
  400. */
  401. public function insert_discount($idremise)
  402. {
  403. // phpcs:enable
  404. global $langs;
  405. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  406. include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  407. $this->db->begin();
  408. $remise = new DiscountAbsolute($this->db);
  409. $result = $remise->fetch($idremise);
  410. if ($result > 0) {
  411. if ($remise->fk_facture) { // Protection against multiple submission
  412. $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
  413. $this->db->rollback();
  414. return -5;
  415. }
  416. $line = new PropaleLigne($this->db);
  417. $this->line->context = $this->context;
  418. $line->fk_propal = $this->id;
  419. $line->fk_remise_except = $remise->id;
  420. $line->desc = $remise->description; // Description ligne
  421. $line->vat_src_code = $remise->vat_src_code;
  422. $line->tva_tx = $remise->tva_tx;
  423. $line->subprice = -$remise->amount_ht;
  424. $line->fk_product = 0; // Id produit predefined
  425. $line->qty = 1;
  426. $line->remise_percent = 0;
  427. $line->rang = -1;
  428. $line->info_bits = 2;
  429. // TODO deprecated
  430. $line->price = -$remise->amount_ht;
  431. $line->total_ht = -$remise->amount_ht;
  432. $line->total_tva = -$remise->amount_tva;
  433. $line->total_ttc = -$remise->amount_ttc;
  434. $result = $line->insert();
  435. if ($result > 0) {
  436. $result = $this->update_price(1);
  437. if ($result > 0) {
  438. $this->db->commit();
  439. return 1;
  440. } else {
  441. $this->db->rollback();
  442. return -1;
  443. }
  444. } else {
  445. $this->error = $line->error;
  446. $this->errors = $line->errors;
  447. $this->db->rollback();
  448. return -2;
  449. }
  450. } else {
  451. $this->db->rollback();
  452. return -2;
  453. }
  454. }
  455. /**
  456. * Add a proposal line into database (linked to product/service or not)
  457. * The parameters are already supposed to be appropriate and with final values to the call
  458. * of this method. Also, for the VAT rate, it must have already been defined
  459. * by whose calling the method get_default_tva (societe_vendeuse, societe_acheteuse, '' product)
  460. * and desc must already have the right value (it's up to the caller to manage multilanguage)
  461. *
  462. * @param string $desc Description of line
  463. * @param float $pu_ht Unit price
  464. * @param float $qty Quantity
  465. * @param float $txtva Force Vat rate, -1 for auto (Can contain the vat_src_code too with syntax '9.9 (CODE)')
  466. * @param float $txlocaltax1 Local tax 1 rate (deprecated, use instead txtva with code inside)
  467. * @param float $txlocaltax2 Local tax 2 rate (deprecated, use instead txtva with code inside)
  468. * @param int $fk_product Product/Service ID predefined
  469. * @param float $remise_percent Pourcentage de remise de la ligne
  470. * @param string $price_base_type HT or TTC
  471. * @param float $pu_ttc Prix unitaire TTC
  472. * @param int $info_bits Bits for type of lines
  473. * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
  474. * @param int $rang Position of line
  475. * @param int $special_code Special code (also used by externals modules!)
  476. * @param int $fk_parent_line Id of parent line
  477. * @param int $fk_fournprice Id supplier price
  478. * @param int $pa_ht Buying price without tax
  479. * @param string $label ???
  480. * @param int $date_start Start date of the line
  481. * @param int $date_end End date of the line
  482. * @param array $array_options extrafields array
  483. * @param string $fk_unit Code of the unit to use. Null to use the default one
  484. * @param string $origin Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be 'orderdet', 'propaldet'..., else 'order','propal,'....
  485. * @param int $origin_id Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be Id of origin object (aka line id), else object id
  486. * @param double $pu_ht_devise Unit price in currency
  487. * @param int $fk_remise_except Id discount if line is from a discount
  488. * @param int $noupdateafterinsertline No update after insert of line
  489. * @return int >0 if OK, <0 if KO
  490. * @see add_product()
  491. */
  492. public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $fk_product = 0, $remise_percent = 0.0, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $origin = '', $origin_id = 0, $pu_ht_devise = 0, $fk_remise_except = 0, $noupdateafterinsertline = 0)
  493. {
  494. global $mysoc, $conf, $langs;
  495. dol_syslog(get_class($this)."::addline propalid=$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, fk_remise_except=".$fk_remise_except);
  496. if ($this->statut == self::STATUS_DRAFT) {
  497. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  498. // Clean parameters
  499. if (empty($remise_percent)) {
  500. $remise_percent = 0;
  501. }
  502. if (empty($qty)) {
  503. $qty = 0;
  504. }
  505. if (empty($info_bits)) {
  506. $info_bits = 0;
  507. }
  508. if (empty($rang)) {
  509. $rang = 0;
  510. }
  511. if (empty($fk_parent_line) || $fk_parent_line < 0) {
  512. $fk_parent_line = 0;
  513. }
  514. $remise_percent = price2num($remise_percent);
  515. $qty = price2num($qty);
  516. $pu_ht = price2num($pu_ht);
  517. $pu_ht_devise = price2num($pu_ht_devise);
  518. $pu_ttc = price2num($pu_ttc);
  519. if (!preg_match('/\((.*)\)/', $txtva)) {
  520. $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
  521. }
  522. $txlocaltax1 = price2num($txlocaltax1);
  523. $txlocaltax2 = price2num($txlocaltax2);
  524. $pa_ht = price2num($pa_ht);
  525. if ($price_base_type == 'HT') {
  526. $pu = $pu_ht;
  527. } else {
  528. $pu = $pu_ttc;
  529. }
  530. // Check parameters
  531. if ($type < 0) {
  532. return -1;
  533. }
  534. if ($date_start && $date_end && $date_start > $date_end) {
  535. $langs->load("errors");
  536. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  537. return -1;
  538. }
  539. $this->db->begin();
  540. $product_type = $type;
  541. if (!empty($fk_product) && $fk_product > 0) {
  542. $product = new Product($this->db);
  543. $result = $product->fetch($fk_product);
  544. $product_type = $product->type;
  545. if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL) && $product_type == 0 && $product->stock_reel < $qty) {
  546. $langs->load("errors");
  547. $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref);
  548. $this->db->rollback();
  549. return -3;
  550. }
  551. }
  552. // Calcul du total TTC et de la TVA pour la ligne a partir de
  553. // qty, pu, remise_percent et txtva
  554. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  555. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  556. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  557. // Clean vat code
  558. $reg = array();
  559. $vat_src_code = '';
  560. $reg = array();
  561. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  562. $vat_src_code = $reg[1];
  563. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  564. }
  565. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
  566. $total_ht = $tabprice[0];
  567. $total_tva = $tabprice[1];
  568. $total_ttc = $tabprice[2];
  569. $total_localtax1 = $tabprice[9];
  570. $total_localtax2 = $tabprice[10];
  571. $pu_ht = $tabprice[3];
  572. $pu_tva = $tabprice[4];
  573. $pu_ttc = $tabprice[5];
  574. // MultiCurrency
  575. $multicurrency_total_ht = $tabprice[16];
  576. $multicurrency_total_tva = $tabprice[17];
  577. $multicurrency_total_ttc = $tabprice[18];
  578. $pu_ht_devise = $tabprice[19];
  579. // Rang to use
  580. $ranktouse = $rang;
  581. if ($ranktouse == -1) {
  582. $rangmax = $this->line_max($fk_parent_line);
  583. $ranktouse = $rangmax + 1;
  584. }
  585. // TODO A virer
  586. // Anciens indicateurs: $price, $remise (a ne plus utiliser)
  587. $price = $pu;
  588. $remise = 0;
  589. if ($remise_percent > 0) {
  590. $remise = round(($pu * $remise_percent / 100), 2);
  591. $price = $pu - $remise;
  592. }
  593. // Insert line
  594. $this->line = new PropaleLigne($this->db);
  595. $this->line->context = $this->context;
  596. $this->line->fk_propal = $this->id;
  597. $this->line->label = $label;
  598. $this->line->desc = $desc;
  599. $this->line->qty = $qty;
  600. $this->line->vat_src_code = $vat_src_code;
  601. $this->line->tva_tx = $txtva;
  602. $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
  603. $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
  604. $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  605. $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  606. $this->line->fk_product = $fk_product;
  607. $this->line->product_type = $type;
  608. $this->line->fk_remise_except = $fk_remise_except;
  609. $this->line->remise_percent = $remise_percent;
  610. $this->line->subprice = $pu_ht;
  611. $this->line->rang = $ranktouse;
  612. $this->line->info_bits = $info_bits;
  613. $this->line->total_ht = $total_ht;
  614. $this->line->total_tva = $total_tva;
  615. $this->line->total_localtax1 = $total_localtax1;
  616. $this->line->total_localtax2 = $total_localtax2;
  617. $this->line->total_ttc = $total_ttc;
  618. $this->line->special_code = $special_code;
  619. $this->line->fk_parent_line = $fk_parent_line;
  620. $this->line->fk_unit = $fk_unit;
  621. $this->line->date_start = $date_start;
  622. $this->line->date_end = $date_end;
  623. $this->line->fk_fournprice = $fk_fournprice;
  624. $this->line->pa_ht = $pa_ht;
  625. $this->line->origin_id = $origin_id;
  626. $this->line->origin = $origin;
  627. // Multicurrency
  628. $this->line->fk_multicurrency = $this->fk_multicurrency;
  629. $this->line->multicurrency_code = $this->multicurrency_code;
  630. $this->line->multicurrency_subprice = $pu_ht_devise;
  631. $this->line->multicurrency_total_ht = $multicurrency_total_ht;
  632. $this->line->multicurrency_total_tva = $multicurrency_total_tva;
  633. $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
  634. // Mise en option de la ligne
  635. if (empty($qty) && empty($special_code)) {
  636. $this->line->special_code = 3;
  637. }
  638. // TODO deprecated
  639. $this->line->price = $price;
  640. if (is_array($array_options) && count($array_options) > 0) {
  641. $this->line->array_options = $array_options;
  642. }
  643. $result = $this->line->insert();
  644. if ($result > 0) {
  645. // Reorder if child line
  646. if (!empty($fk_parent_line)) {
  647. $this->line_order(true, 'DESC');
  648. } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) { // Update all rank of all other lines
  649. $linecount = count($this->lines);
  650. for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
  651. $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
  652. }
  653. }
  654. // Mise a jour informations denormalisees au niveau de la propale meme
  655. if (empty($noupdateafterinsertline)) {
  656. $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
  657. }
  658. if ($result > 0) {
  659. $this->db->commit();
  660. return $this->line->id;
  661. } else {
  662. $this->error = $this->db->error();
  663. $this->db->rollback();
  664. return -1;
  665. }
  666. } else {
  667. $this->error = $this->line->error;
  668. $this->errors = $this->line->errors;
  669. $this->db->rollback();
  670. return -2;
  671. }
  672. } else {
  673. dol_syslog(get_class($this)."::addline status of proposal must be Draft to allow use of ->addline()", LOG_ERR);
  674. return -3;
  675. }
  676. }
  677. /**
  678. * Update a proposal line
  679. *
  680. * @param int $rowid Id of line
  681. * @param float $pu Unit price (HT or TTC depending on price_base_type)
  682. * @param float $qty Quantity
  683. * @param float $remise_percent Discount on line
  684. * @param float $txtva VAT Rate (Can be '1.23' or '1.23 (ABC)')
  685. * @param float $txlocaltax1 Local tax 1 rate
  686. * @param float $txlocaltax2 Local tax 2 rate
  687. * @param string $desc Description
  688. * @param string $price_base_type HT or TTC
  689. * @param int $info_bits Miscellaneous informations
  690. * @param int $special_code Special code (also used by externals modules!)
  691. * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines).
  692. * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules)
  693. * @param int $fk_fournprice Id of origin supplier price
  694. * @param int $pa_ht Price (without tax) of product when it was bought
  695. * @param string $label ???
  696. * @param int $type 0/1=Product/service
  697. * @param int $date_start Start date of the line
  698. * @param int $date_end End date of the line
  699. * @param array $array_options extrafields array
  700. * @param string $fk_unit Code of the unit to use. Null to use the default one
  701. * @param double $pu_ht_devise Unit price in currency
  702. * @param int $notrigger disable line update trigger
  703. * @param integer $rang line rank
  704. * @return int 0 if OK, <0 if KO
  705. */
  706. public function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.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, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $rang = 0)
  707. {
  708. global $mysoc, $langs;
  709. dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent,
  710. txtva=$txtva, desc=$desc, price_base_type=$price_base_type, info_bits=$info_bits, special_code=$special_code, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, type=$type, date_start=$date_start, date_end=$date_end");
  711. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  712. // Clean parameters
  713. $remise_percent = price2num($remise_percent);
  714. $qty = price2num($qty);
  715. $pu = price2num($pu);
  716. $pu_ht_devise = price2num($pu_ht_devise);
  717. if (!preg_match('/\((.*)\)/', $txtva)) {
  718. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  719. }
  720. $txlocaltax1 = price2num($txlocaltax1);
  721. $txlocaltax2 = price2num($txlocaltax2);
  722. $pa_ht = price2num($pa_ht);
  723. if (empty($qty) && empty($special_code)) {
  724. $special_code = 3; // Set option tag
  725. }
  726. if (!empty($qty) && $special_code == 3) {
  727. $special_code = 0; // Remove option tag
  728. }
  729. if (empty($type)) {
  730. $type = 0;
  731. }
  732. if ($date_start && $date_end && $date_start > $date_end) {
  733. $langs->load("errors");
  734. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  735. return -1;
  736. }
  737. if ($this->statut == self::STATUS_DRAFT) {
  738. $this->db->begin();
  739. // Calcul du total TTC et de la TVA pour la ligne a partir de
  740. // qty, pu, remise_percent et txtva
  741. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  742. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  743. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  744. // Clean vat code
  745. $reg = array();
  746. $vat_src_code = '';
  747. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  748. $vat_src_code = $reg[1];
  749. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  750. }
  751. // TODO Implement if (getDolGlobalInt('MAIN_UNIT_PRICE_WITH_TAX_IS_FOR_ALL_TAXES')) ?
  752. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
  753. $total_ht = $tabprice[0];
  754. $total_tva = $tabprice[1];
  755. $total_ttc = $tabprice[2];
  756. $total_localtax1 = $tabprice[9];
  757. $total_localtax2 = $tabprice[10];
  758. $pu_ht = $tabprice[3];
  759. $pu_tva = $tabprice[4];
  760. $pu_ttc = $tabprice[5];
  761. // MultiCurrency
  762. $multicurrency_total_ht = $tabprice[16];
  763. $multicurrency_total_tva = $tabprice[17];
  764. $multicurrency_total_ttc = $tabprice[18];
  765. $pu_ht_devise = $tabprice[19];
  766. // Anciens indicateurs: $price, $remise (a ne plus utiliser)
  767. $price = $pu;
  768. $remise = 0;
  769. if ($remise_percent > 0) {
  770. $remise = round(($pu * $remise_percent / 100), 2);
  771. $price = $pu - $remise;
  772. }
  773. //Fetch current line from the database and then clone the object and set it in $oldline property
  774. $line = new PropaleLigne($this->db);
  775. $line->fetch($rowid);
  776. $staticline = clone $line;
  777. $line->oldline = $staticline;
  778. $this->line = $line;
  779. $this->line->context = $this->context;
  780. $this->line->rang = $rang;
  781. // Reorder if fk_parent_line change
  782. if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
  783. $rangmax = $this->line_max($fk_parent_line);
  784. $this->line->rang = $rangmax + 1;
  785. }
  786. $this->line->id = $rowid;
  787. $this->line->label = $label;
  788. $this->line->desc = $desc;
  789. $this->line->qty = $qty;
  790. $this->line->product_type = $type;
  791. $this->line->vat_src_code = $vat_src_code;
  792. $this->line->tva_tx = $txtva;
  793. $this->line->localtax1_tx = $txlocaltax1;
  794. $this->line->localtax2_tx = $txlocaltax2;
  795. $this->line->localtax1_type = $localtaxes_type[0];
  796. $this->line->localtax2_type = $localtaxes_type[2];
  797. $this->line->remise_percent = $remise_percent;
  798. $this->line->subprice = $pu_ht;
  799. $this->line->info_bits = $info_bits;
  800. $this->line->total_ht = $total_ht;
  801. $this->line->total_tva = $total_tva;
  802. $this->line->total_localtax1 = $total_localtax1;
  803. $this->line->total_localtax2 = $total_localtax2;
  804. $this->line->total_ttc = $total_ttc;
  805. $this->line->special_code = $special_code;
  806. $this->line->fk_parent_line = $fk_parent_line;
  807. $this->line->skip_update_total = $skip_update_total;
  808. $this->line->fk_unit = $fk_unit;
  809. $this->line->fk_fournprice = $fk_fournprice;
  810. $this->line->pa_ht = $pa_ht;
  811. $this->line->date_start = $date_start;
  812. $this->line->date_end = $date_end;
  813. if (is_array($array_options) && count($array_options) > 0) {
  814. // We replace values in this->line->array_options only for entries defined into $array_options
  815. foreach ($array_options as $key => $value) {
  816. $this->line->array_options[$key] = $array_options[$key];
  817. }
  818. }
  819. // Multicurrency
  820. $this->line->multicurrency_subprice = $pu_ht_devise;
  821. $this->line->multicurrency_total_ht = $multicurrency_total_ht;
  822. $this->line->multicurrency_total_tva = $multicurrency_total_tva;
  823. $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
  824. $result = $this->line->update($notrigger);
  825. if ($result > 0) {
  826. // Reorder if child line
  827. if (!empty($fk_parent_line)) {
  828. $this->line_order(true, 'DESC');
  829. }
  830. $this->update_price(1);
  831. $this->fk_propal = $this->id;
  832. $this->rowid = $rowid;
  833. $this->db->commit();
  834. return $result;
  835. } else {
  836. $this->error = $this->line->error;
  837. $this->errors = $this->line->errors;
  838. $this->db->rollback();
  839. return -1;
  840. }
  841. } else {
  842. dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action");
  843. return -2;
  844. }
  845. }
  846. /**
  847. * Delete detail line
  848. *
  849. * @param int $lineid Id of line to delete
  850. * @return int >0 if OK, <0 if KO
  851. */
  852. public function deleteline($lineid)
  853. {
  854. global $user;
  855. if ($this->statut == self::STATUS_DRAFT) {
  856. $this->db->begin();
  857. $line = new PropaleLigne($this->db);
  858. // For triggers
  859. $line->fetch($lineid);
  860. if ($line->delete($user) > 0) {
  861. $this->update_price(1);
  862. $this->db->commit();
  863. return 1;
  864. } else {
  865. $this->error = $line->error;
  866. $this->errors = $line->errors;
  867. $this->db->rollback();
  868. return -1;
  869. }
  870. } else {
  871. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  872. return -2;
  873. }
  874. }
  875. /**
  876. * Create commercial proposal into database
  877. * this->ref can be set or empty. If empty, we will use "(PROVid)"
  878. *
  879. * @param User $user User that create
  880. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  881. * @return int <0 if KO, >=0 if OK
  882. */
  883. public function create($user, $notrigger = 0)
  884. {
  885. global $conf, $hookmanager, $mysoc;
  886. $error = 0;
  887. $now = dol_now();
  888. // Clean parameters
  889. if (empty($this->date)) {
  890. $this->date = $this->datep;
  891. }
  892. $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
  893. if (empty($this->availability_id)) {
  894. $this->availability_id = 0;
  895. }
  896. if (empty($this->demand_reason_id)) {
  897. $this->demand_reason_id = 0;
  898. }
  899. // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
  900. if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
  901. list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
  902. } else {
  903. $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  904. }
  905. if (empty($this->fk_multicurrency)) {
  906. $this->multicurrency_code = $conf->currency;
  907. $this->fk_multicurrency = 0;
  908. $this->multicurrency_tx = 1;
  909. }
  910. // Set tmp vars
  911. $delivery_date = empty($this->delivery_date) ? $this->date_livraison : $this->delivery_date;
  912. dol_syslog(get_class($this)."::create");
  913. // Check parameters
  914. $result = $this->fetch_thirdparty();
  915. if ($result < 0) {
  916. $this->error = "Failed to fetch company";
  917. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  918. return -3;
  919. }
  920. // Check parameters
  921. if (!empty($this->ref)) { // We check that ref is not already used
  922. $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
  923. if ($result > 0) {
  924. $this->error = 'ErrorRefAlreadyExists';
  925. dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
  926. $this->db->rollback();
  927. return -1;
  928. }
  929. }
  930. if (empty($this->date)) {
  931. $this->error = "Date of proposal is required";
  932. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  933. return -4;
  934. }
  935. $this->db->begin();
  936. // Insert into database
  937. $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal (";
  938. $sql .= "fk_soc";
  939. $sql .= ", price";
  940. $sql .= ", remise";
  941. $sql .= ", remise_percent";
  942. $sql .= ", remise_absolue";
  943. $sql .= ", total_tva";
  944. $sql .= ", total_ttc";
  945. $sql .= ", datep";
  946. $sql .= ", datec";
  947. $sql .= ", ref";
  948. $sql .= ", fk_user_author";
  949. $sql .= ", note_private";
  950. $sql .= ", note_public";
  951. $sql .= ", model_pdf";
  952. $sql .= ", fin_validite";
  953. $sql .= ", fk_cond_reglement";
  954. $sql .= ", deposit_percent";
  955. $sql .= ", fk_mode_reglement";
  956. $sql .= ", fk_account";
  957. $sql .= ", ref_client";
  958. $sql .= ", ref_ext";
  959. $sql .= ", date_livraison";
  960. $sql .= ", fk_shipping_method";
  961. $sql .= ", fk_warehouse";
  962. $sql .= ", fk_availability";
  963. $sql .= ", fk_input_reason";
  964. $sql .= ", fk_projet";
  965. $sql .= ", fk_incoterms";
  966. $sql .= ", location_incoterms";
  967. $sql .= ", entity";
  968. $sql .= ", fk_multicurrency";
  969. $sql .= ", multicurrency_code";
  970. $sql .= ", multicurrency_tx";
  971. $sql .= ") ";
  972. $sql .= " VALUES (";
  973. $sql .= $this->socid;
  974. $sql .= ", 0";
  975. $sql .= ", ".((float) $this->remise); // deprecated
  976. $sql .= ", ".($this->remise_percent ? ((float) $this->remise_percent) : 'NULL');
  977. $sql .= ", ".($this->remise_absolue ? ((float) $this->remise_absolue) : 'NULL'); // deprecated
  978. $sql .= ", 0";
  979. $sql .= ", 0";
  980. $sql .= ", '".$this->db->idate($this->date)."'";
  981. $sql .= ", '".$this->db->idate($now)."'";
  982. $sql .= ", '(PROV)'";
  983. $sql .= ", ".($user->id > 0 ? ((int) $user->id) : "NULL");
  984. $sql .= ", '".$this->db->escape($this->note_private)."'";
  985. $sql .= ", '".$this->db->escape($this->note_public)."'";
  986. $sql .= ", '".$this->db->escape($this->model_pdf)."'";
  987. $sql .= ", ".($this->fin_validite != '' ? "'".$this->db->idate($this->fin_validite)."'" : "NULL");
  988. $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : 'NULL');
  989. $sql .= ", ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : 'NULL');
  990. $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : 'NULL');
  991. $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
  992. $sql .= ", '".$this->db->escape($this->ref_client)."'";
  993. $sql .= ", '".$this->db->escape($this->ref_ext)."'";
  994. $sql .= ", ".(empty($delivery_date) ? "NULL" : "'".$this->db->idate($delivery_date)."'");
  995. $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL');
  996. $sql .= ", ".($this->warehouse_id > 0 ? $this->warehouse_id : 'NULL');
  997. $sql .= ", ".$this->availability_id;
  998. $sql .= ", ".$this->demand_reason_id;
  999. $sql .= ", ".($this->fk_project ? $this->fk_project : "null");
  1000. $sql .= ", ".(int) $this->fk_incoterms;
  1001. $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
  1002. $sql .= ", ".setEntity($this);
  1003. $sql .= ", ".(int) $this->fk_multicurrency;
  1004. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  1005. $sql .= ", ".(double) $this->multicurrency_tx;
  1006. $sql .= ")";
  1007. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  1008. $resql = $this->db->query($sql);
  1009. if ($resql) {
  1010. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal");
  1011. if ($this->id) {
  1012. $this->ref = '(PROV'.$this->id.')';
  1013. $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
  1014. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  1015. $resql = $this->db->query($sql);
  1016. if (!$resql) {
  1017. $error++;
  1018. }
  1019. if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
  1020. $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
  1021. }
  1022. // Add object linked
  1023. if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
  1024. foreach ($this->linked_objects as $origin => $tmp_origin_id) {
  1025. 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, ...))
  1026. foreach ($tmp_origin_id as $origin_id) {
  1027. $ret = $this->add_object_linked($origin, $origin_id);
  1028. if (!$ret) {
  1029. $this->error = $this->db->lasterror();
  1030. $error++;
  1031. }
  1032. }
  1033. } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
  1034. {
  1035. $origin_id = $tmp_origin_id;
  1036. $ret = $this->add_object_linked($origin, $origin_id);
  1037. if (!$ret) {
  1038. $this->error = $this->db->lasterror();
  1039. $error++;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. /*
  1045. * Insertion du detail des produits dans la base
  1046. * Insert products detail in database
  1047. */
  1048. if (!$error) {
  1049. $fk_parent_line = 0;
  1050. $num = count($this->lines);
  1051. for ($i = 0; $i < $num; $i++) {
  1052. if (!is_object($this->lines[$i])) { // If this->lines is not array of objects, coming from REST API
  1053. // Convert into object this->lines[$i].
  1054. $line = (object) $this->lines[$i];
  1055. } else {
  1056. $line = $this->lines[$i];
  1057. }
  1058. // Reset fk_parent_line for line that are not child lines or special product
  1059. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  1060. $fk_parent_line = 0;
  1061. }
  1062. // Complete vat rate with code
  1063. $vatrate = $line->tva_tx;
  1064. if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) {
  1065. $vatrate .= ' ('.$line->vat_src_code.')';
  1066. }
  1067. if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) {
  1068. $originid = $line->origin_id;
  1069. $origintype = $line->origin;
  1070. } else {
  1071. $originid = $line->id;
  1072. $origintype = $this->element;
  1073. }
  1074. $result = $this->addline(
  1075. $line->desc,
  1076. $line->subprice,
  1077. $line->qty,
  1078. $vatrate,
  1079. $line->localtax1_tx,
  1080. $line->localtax2_tx,
  1081. $line->fk_product,
  1082. $line->remise_percent,
  1083. 'HT',
  1084. 0,
  1085. $line->info_bits,
  1086. $line->product_type,
  1087. $line->rang,
  1088. $line->special_code,
  1089. $fk_parent_line,
  1090. $line->fk_fournprice,
  1091. $line->pa_ht,
  1092. $line->label,
  1093. $line->date_start,
  1094. $line->date_end,
  1095. $line->array_options,
  1096. $line->fk_unit,
  1097. $origintype,
  1098. $originid,
  1099. 0,
  1100. 0,
  1101. 1
  1102. );
  1103. if ($result < 0) {
  1104. $error++;
  1105. $this->error = $this->db->error;
  1106. dol_print_error($this->db);
  1107. break;
  1108. }
  1109. // Defined the new fk_parent_line
  1110. if ($result > 0 && $line->product_type == 9) {
  1111. $fk_parent_line = $result;
  1112. }
  1113. }
  1114. }
  1115. // Set delivery address
  1116. /*if (! $error && $this->fk_delivery_address)
  1117. {
  1118. $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
  1119. $sql.= " SET fk_delivery_address = ".((int) $this->fk_delivery_address);
  1120. $sql.= " WHERE ref = '".$this->db->escape($this->ref)."'";
  1121. $sql.= " AND entity = ".setEntity($this);
  1122. $result=$this->db->query($sql);
  1123. }*/
  1124. if (!$error) {
  1125. // Mise a jour infos denormalisees
  1126. $resql = $this->update_price(1, 'auto', 0, $mysoc);
  1127. if ($resql) {
  1128. $action = 'update';
  1129. // Actions on extra fields
  1130. if (!$error) {
  1131. $result = $this->insertExtraFields();
  1132. if ($result < 0) {
  1133. $error++;
  1134. }
  1135. }
  1136. if (!$error && !$notrigger) {
  1137. // Call trigger
  1138. $result = $this->call_trigger('PROPAL_CREATE', $user);
  1139. if ($result < 0) {
  1140. $error++;
  1141. }
  1142. // End call triggers
  1143. }
  1144. } else {
  1145. $this->error = $this->db->lasterror();
  1146. $error++;
  1147. }
  1148. }
  1149. } else {
  1150. $this->error = $this->db->lasterror();
  1151. $error++;
  1152. }
  1153. if (!$error) {
  1154. $this->db->commit();
  1155. dol_syslog(get_class($this)."::create done id=".$this->id);
  1156. return $this->id;
  1157. } else {
  1158. $this->db->rollback();
  1159. return -2;
  1160. }
  1161. } else {
  1162. $this->error = $this->db->lasterror();
  1163. $this->db->rollback();
  1164. return -1;
  1165. }
  1166. }
  1167. /**
  1168. * Load an object from its id and create a new one in database
  1169. *
  1170. * @param User $user User making the clone
  1171. * @param int $socid Id of thirdparty
  1172. * @param int $forceentity Entity id to force
  1173. * @param bool $update_prices [=false] Update prices if true
  1174. * @return int New id of clone
  1175. */
  1176. public function createFromClone(User $user, $socid = 0, $forceentity = null, $update_prices = false)
  1177. {
  1178. global $conf, $hookmanager, $mysoc;
  1179. dol_include_once('/projet/class/project.class.php');
  1180. $error = 0;
  1181. $now = dol_now();
  1182. dol_syslog(__METHOD__, LOG_DEBUG);
  1183. $object = new self($this->db);
  1184. $this->db->begin();
  1185. // Load source object
  1186. $object->fetch($this->id);
  1187. $objsoc = new Societe($this->db);
  1188. // Change socid if needed
  1189. if (!empty($socid) && $socid != $object->socid) {
  1190. if ($objsoc->fetch($socid) > 0) {
  1191. $object->socid = $objsoc->id;
  1192. $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
  1193. $object->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : null);
  1194. $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
  1195. $object->fk_delivery_address = '';
  1196. /*if (isModEnabled('project'))
  1197. {
  1198. $project = new Project($db);
  1199. if ($this->fk_project > 0 && $project->fetch($this->fk_project)) {
  1200. if ($project->socid <= 0) $clonedObj->fk_project = $this->fk_project;
  1201. else $clonedObj->fk_project = '';
  1202. } else {
  1203. $clonedObj->fk_project = '';
  1204. }
  1205. }*/
  1206. $object->fk_project = ''; // A cloned proposal is set by default to no project.
  1207. }
  1208. // reset ref_client
  1209. $object->ref_client = '';
  1210. // TODO Change product price if multi-prices
  1211. } else {
  1212. $objsoc->fetch($object->socid);
  1213. }
  1214. // update prices
  1215. if ($update_prices === true) {
  1216. if ($objsoc->id > 0 && !empty($object->lines)) {
  1217. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  1218. // If price per customer
  1219. require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
  1220. }
  1221. foreach ($object->lines as $line) {
  1222. if ($line->fk_product > 0) {
  1223. $prod = new Product($this->db);
  1224. $res = $prod->fetch($line->fk_product);
  1225. if ($res > 0) {
  1226. $pu_ht = $prod->price;
  1227. $tva_tx = get_default_tva($mysoc, $objsoc, $prod->id);
  1228. $remise_percent = $objsoc->remise_percent;
  1229. if (!empty($conf->global->PRODUIT_MULTIPRICES) && $objsoc->price_level > 0) {
  1230. $pu_ht = $prod->multiprices[$objsoc->price_level];
  1231. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  1232. if (isset($prod->multiprices_tva_tx[$objsoc->price_level])) {
  1233. $tva_tx = $prod->multiprices_tva_tx[$objsoc->price_level];
  1234. }
  1235. }
  1236. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  1237. $prodcustprice = new Productcustomerprice($this->db);
  1238. $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $objsoc->id);
  1239. $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
  1240. if ($result) {
  1241. // If there is some prices specific to the customer
  1242. if (count($prodcustprice->lines) > 0) {
  1243. $pu_ht = price($prodcustprice->lines[0]->price);
  1244. $tva_tx = ($prodcustprice->lines[0]->default_vat_code ? $prodcustprice->lines[0]->tva_tx.' ('.$prodcustprice->lines[0]->default_vat_code.' )' : $prodcustprice->lines[0]->tva_tx);
  1245. if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
  1246. $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
  1247. }
  1248. }
  1249. }
  1250. }
  1251. $line->subprice = $pu_ht;
  1252. $line->tva_tx = $tva_tx;
  1253. $line->remise_percent = $remise_percent;
  1254. }
  1255. }
  1256. }
  1257. }
  1258. }
  1259. $object->id = 0;
  1260. $object->ref = '';
  1261. $object->entity = (!empty($forceentity) ? $forceentity : $object->entity);
  1262. $object->statut = self::STATUS_DRAFT;
  1263. // Clear fields
  1264. $object->user_author = $user->id;
  1265. $object->user_valid = 0;
  1266. $object->date = $now;
  1267. $object->datep = $now; // deprecated
  1268. $object->fin_validite = $object->date + ($object->duree_validite * 24 * 3600);
  1269. if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) {
  1270. $object->ref_client = '';
  1271. }
  1272. if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
  1273. $object->note_private = '';
  1274. $object->note_public = '';
  1275. }
  1276. // Create clone
  1277. $object->context['createfromclone'] = 'createfromclone';
  1278. $result = $object->create($user);
  1279. if ($result < 0) {
  1280. $this->error = $object->error;
  1281. $this->errors = array_merge($this->errors, $object->errors);
  1282. $error++;
  1283. }
  1284. if (!$error) {
  1285. // copy internal contacts
  1286. if ($object->copy_linked_contact($this, 'internal') < 0) {
  1287. $error++;
  1288. }
  1289. }
  1290. if (!$error) {
  1291. // copy external contacts if same company
  1292. if ($this->socid == $object->socid) {
  1293. if ($object->copy_linked_contact($this, 'external') < 0) {
  1294. $error++;
  1295. }
  1296. }
  1297. }
  1298. if (!$error) {
  1299. // Hook of thirdparty module
  1300. if (is_object($hookmanager)) {
  1301. $parameters = array('objFrom'=>$this, 'clonedObj'=>$object);
  1302. $action = '';
  1303. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  1304. if ($reshook < 0) {
  1305. $this->errors += $hookmanager->errors;
  1306. $this->error = $hookmanager->error;
  1307. $error++;
  1308. }
  1309. }
  1310. }
  1311. unset($object->context['createfromclone']);
  1312. // End
  1313. if (!$error) {
  1314. $this->db->commit();
  1315. return $object->id;
  1316. } else {
  1317. $this->db->rollback();
  1318. return -1;
  1319. }
  1320. }
  1321. /**
  1322. * Load a proposal from database. Get also lines.
  1323. *
  1324. * @param int $rowid Id of object to load
  1325. * @param string $ref Ref of proposal
  1326. * @param string $ref_ext Ref ext of proposal
  1327. * @param int $forceentity Entity id to force when searching on ref or ref_ext
  1328. * @return int >0 if OK, <0 if KO
  1329. */
  1330. public function fetch($rowid, $ref = '', $ref_ext = '', $forceentity = 0)
  1331. {
  1332. $sql = "SELECT p.rowid, p.ref, p.entity, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc";
  1333. $sql .= ", p.total_ttc, p.total_tva, p.localtax1, p.localtax2, p.total_ht";
  1334. $sql .= ", p.datec";
  1335. $sql .= ", p.date_signature as dates";
  1336. $sql .= ", p.date_valid as datev";
  1337. $sql .= ", p.datep as dp";
  1338. $sql .= ", p.fin_validite as dfv";
  1339. $sql .= ", p.date_livraison as delivery_date";
  1340. $sql .= ", p.model_pdf, p.last_main_doc, p.ref_client, ref_ext, p.extraparams";
  1341. $sql .= ", p.note_private, p.note_public";
  1342. $sql .= ", p.fk_projet as fk_project, p.fk_statut";
  1343. $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
  1344. $sql .= ", p.fk_delivery_address";
  1345. $sql .= ", p.fk_availability";
  1346. $sql .= ", p.fk_input_reason";
  1347. $sql .= ", p.fk_cond_reglement";
  1348. $sql .= ", p.fk_mode_reglement";
  1349. $sql .= ', p.fk_account';
  1350. $sql .= ", p.fk_shipping_method";
  1351. $sql .= ", p.fk_warehouse";
  1352. $sql .= ", p.fk_incoterms, p.location_incoterms";
  1353. $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
  1354. $sql .= ", p.tms as date_modification";
  1355. $sql .= ", i.libelle as label_incoterms";
  1356. $sql .= ", c.label as statut_label";
  1357. $sql .= ", ca.code as availability_code, ca.label as availability";
  1358. $sql .= ", dr.code as demand_reason_code, dr.label as demand_reason";
  1359. $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc, p.deposit_percent";
  1360. $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
  1361. $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
  1362. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_propalst as c ON p.fk_statut = c.id';
  1363. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')';
  1364. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')';
  1365. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid';
  1366. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid';
  1367. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid';
  1368. if (!empty($ref)) {
  1369. if (!empty($forceentity)) {
  1370. $sql .= " WHERE p.entity = ".(int) $forceentity; // Check only the current entity because we may have the same reference in several entities
  1371. } else {
  1372. $sql .= " WHERE p.entity IN (".getEntity('propal').")";
  1373. }
  1374. $sql .= " AND p.ref='".$this->db->escape($ref)."'";
  1375. } else {
  1376. // Dont't use entity if you use rowid
  1377. $sql .= " WHERE p.rowid = ".((int) $rowid);
  1378. }
  1379. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  1380. $resql = $this->db->query($sql);
  1381. if ($resql) {
  1382. if ($this->db->num_rows($resql)) {
  1383. $obj = $this->db->fetch_object($resql);
  1384. $this->id = $obj->rowid;
  1385. $this->entity = $obj->entity;
  1386. $this->ref = $obj->ref;
  1387. $this->ref_client = $obj->ref_client;
  1388. $this->ref_ext = $obj->ref_ext;
  1389. $this->remise = $obj->remise;
  1390. $this->remise_percent = $obj->remise_percent;
  1391. $this->remise_absolue = $obj->remise_absolue;
  1392. $this->total = $obj->total_ttc; // TODO deprecated
  1393. $this->total_ttc = $obj->total_ttc;
  1394. $this->total_ht = $obj->total_ht;
  1395. $this->total_tva = $obj->total_tva;
  1396. $this->total_localtax1 = $obj->localtax1;
  1397. $this->total_localtax2 = $obj->localtax2;
  1398. $this->socid = $obj->fk_soc;
  1399. $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
  1400. $this->fk_project = $obj->fk_project;
  1401. $this->project = null; // Clear if another value was already set by fetch_projet
  1402. $this->model_pdf = $obj->model_pdf;
  1403. $this->modelpdf = $obj->model_pdf; // deprecated
  1404. $this->last_main_doc = $obj->last_main_doc;
  1405. $this->note = $obj->note_private; // TODO deprecated
  1406. $this->note_private = $obj->note_private;
  1407. $this->note_public = $obj->note_public;
  1408. $this->status = (int) $obj->fk_statut;
  1409. $this->statut = $this->status; // deprecated
  1410. $this->statut_libelle = $obj->statut_label;
  1411. $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
  1412. $this->datev = $this->db->jdate($obj->datev); // TODO deprecated
  1413. $this->date_creation = $this->db->jdate($obj->datec); //Creation date
  1414. $this->date_validation = $this->db->jdate($obj->datev); //Validation date
  1415. $this->date_modification = $this->db->jdate($obj->date_modification); // tms
  1416. $this->date_signature = $this->db->jdate($obj->dates); // Signature date
  1417. $this->date = $this->db->jdate($obj->dp); // Proposal date
  1418. $this->datep = $this->db->jdate($obj->dp); // deprecated
  1419. $this->fin_validite = $this->db->jdate($obj->dfv);
  1420. $this->date_livraison = $this->db->jdate($obj->delivery_date); // deprecated
  1421. $this->delivery_date = $this->db->jdate($obj->delivery_date);
  1422. $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
  1423. $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null;
  1424. $this->availability_id = $obj->fk_availability;
  1425. $this->availability_code = $obj->availability_code;
  1426. $this->availability = $obj->availability;
  1427. $this->demand_reason_id = $obj->fk_input_reason;
  1428. $this->demand_reason_code = $obj->demand_reason_code;
  1429. $this->demand_reason = $obj->demand_reason;
  1430. $this->fk_address = $obj->fk_delivery_address;
  1431. $this->mode_reglement_id = $obj->fk_mode_reglement;
  1432. $this->mode_reglement_code = $obj->mode_reglement_code;
  1433. $this->mode_reglement = $obj->mode_reglement;
  1434. $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
  1435. $this->cond_reglement_id = $obj->fk_cond_reglement;
  1436. $this->cond_reglement_code = $obj->cond_reglement_code;
  1437. $this->cond_reglement = $obj->cond_reglement;
  1438. $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
  1439. $this->deposit_percent = $obj->deposit_percent;
  1440. $this->extraparams = (array) json_decode($obj->extraparams, true);
  1441. $this->user_author_id = $obj->fk_user_author;
  1442. $this->user_valid_id = $obj->fk_user_valid;
  1443. $this->user_close_id = $obj->fk_user_cloture;
  1444. //Incoterms
  1445. $this->fk_incoterms = $obj->fk_incoterms;
  1446. $this->location_incoterms = $obj->location_incoterms;
  1447. $this->label_incoterms = $obj->label_incoterms;
  1448. // Multicurrency
  1449. $this->fk_multicurrency = $obj->fk_multicurrency;
  1450. $this->multicurrency_code = $obj->multicurrency_code;
  1451. $this->multicurrency_tx = $obj->multicurrency_tx;
  1452. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  1453. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  1454. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  1455. if ($obj->fk_statut == self::STATUS_DRAFT) {
  1456. $this->brouillon = 1;
  1457. }
  1458. // Retrieve all extrafield
  1459. // fetch optionals attributes and labels
  1460. $this->fetch_optionals();
  1461. $this->db->free($resql);
  1462. $this->lines = array();
  1463. // Lines
  1464. $result = $this->fetch_lines();
  1465. if ($result < 0) {
  1466. return -3;
  1467. }
  1468. return 1;
  1469. }
  1470. $this->error = "Record Not Found";
  1471. return 0;
  1472. } else {
  1473. $this->error = $this->db->lasterror();
  1474. return -1;
  1475. }
  1476. }
  1477. /**
  1478. * Update database
  1479. *
  1480. * @param User $user User that modify
  1481. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  1482. * @return int <0 if KO, >0 if OK
  1483. */
  1484. public function update(User $user, $notrigger = 0)
  1485. {
  1486. global $conf;
  1487. $error = 0;
  1488. // Clean parameters
  1489. if (isset($this->ref)) {
  1490. $this->ref = trim($this->ref);
  1491. }
  1492. if (isset($this->ref_client)) {
  1493. $this->ref_client = trim($this->ref_client);
  1494. }
  1495. if (isset($this->note) || isset($this->note_private)) {
  1496. $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
  1497. }
  1498. if (isset($this->note_public)) {
  1499. $this->note_public = trim($this->note_public);
  1500. }
  1501. if (isset($this->model_pdf)) {
  1502. $this->model_pdf = trim($this->model_pdf);
  1503. }
  1504. if (isset($this->import_key)) {
  1505. $this->import_key = trim($this->import_key);
  1506. }
  1507. if (!empty($this->duree_validite) && is_numeric($this->duree_validite)) {
  1508. $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
  1509. }
  1510. // Check parameters
  1511. // Put here code to add control on parameters values
  1512. // Update request
  1513. $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET";
  1514. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
  1515. $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
  1516. $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
  1517. $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
  1518. $sql .= " datep=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
  1519. if (!empty($this->fin_validite)) {
  1520. $sql .= " fin_validite=".(strval($this->fin_validite) != '' ? "'".$this->db->idate($this->fin_validite)."'" : 'null').",";
  1521. }
  1522. $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
  1523. $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
  1524. $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
  1525. $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
  1526. $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
  1527. $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
  1528. $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
  1529. $sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").",";
  1530. $sql .= " fk_user_valid=".(isset($this->user_valid) ? $this->user_valid : "null").",";
  1531. $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
  1532. $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
  1533. $sql .= " deposit_percent=".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null").",";
  1534. $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").",";
  1535. $sql .= " fk_input_reason=".(isset($this->demand_reason_id) ? $this->demand_reason_id : "null").",";
  1536. $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
  1537. $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
  1538. $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
  1539. $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
  1540. $sql .= " WHERE rowid=".((int) $this->id);
  1541. $this->db->begin();
  1542. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  1543. $resql = $this->db->query($sql);
  1544. if (!$resql) {
  1545. $error++;
  1546. $this->errors[] = "Error ".$this->db->lasterror();
  1547. }
  1548. if (!$error) {
  1549. $result = $this->insertExtraFields();
  1550. if ($result < 0) {
  1551. $error++;
  1552. }
  1553. }
  1554. if (!$error && !$notrigger) {
  1555. // Call trigger
  1556. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  1557. if ($result < 0) {
  1558. $error++;
  1559. }
  1560. // End call triggers
  1561. }
  1562. // Commit or rollback
  1563. if ($error) {
  1564. foreach ($this->errors as $errmsg) {
  1565. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  1566. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1567. }
  1568. $this->db->rollback();
  1569. return -1 * $error;
  1570. } else {
  1571. $this->db->commit();
  1572. return 1;
  1573. }
  1574. }
  1575. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1576. /**
  1577. * Load array lines
  1578. *
  1579. * @param int $only_product Return only physical products
  1580. * @param int $loadalsotranslation Return translation for products
  1581. * @param string $filters Filter on other fields
  1582. *
  1583. * @return int <0 if KO, >0 if OK
  1584. */
  1585. public function fetch_lines($only_product = 0, $loadalsotranslation = 0, $filters = '')
  1586. {
  1587. // phpcs:enable
  1588. global $langs, $conf;
  1589. $this->lines = array();
  1590. $sql = 'SELECT d.rowid, d.fk_propal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,';
  1591. $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,';
  1592. $sql .= ' d.fk_unit,';
  1593. $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_tobatch, p.barcode as product_barcode,';
  1594. $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units,';
  1595. $sql .= ' d.date_start, d.date_end,';
  1596. $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc';
  1597. $sql .= ' FROM '.MAIN_DB_PREFIX.'propaldet as d';
  1598. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)';
  1599. $sql .= ' WHERE d.fk_propal = '.((int) $this->id);
  1600. if ($only_product) {
  1601. $sql .= ' AND p.fk_product_type = 0';
  1602. }
  1603. if ($filters) {
  1604. $sql .= $filters;
  1605. }
  1606. $sql .= ' ORDER by d.rang';
  1607. dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
  1608. $result = $this->db->query($sql);
  1609. if ($result) {
  1610. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  1611. $num = $this->db->num_rows($result);
  1612. $i = 0;
  1613. while ($i < $num) {
  1614. $objp = $this->db->fetch_object($result);
  1615. $line = new PropaleLigne($this->db);
  1616. $line->rowid = $objp->rowid; //Deprecated
  1617. $line->id = $objp->rowid;
  1618. $line->fk_propal = $objp->fk_propal;
  1619. $line->fk_parent_line = $objp->fk_parent_line;
  1620. $line->product_type = $objp->product_type;
  1621. $line->label = $objp->custom_label;
  1622. $line->desc = $objp->description; // Description ligne
  1623. $line->description = $objp->description; // Description ligne
  1624. $line->qty = $objp->qty;
  1625. $line->vat_src_code = $objp->vat_src_code;
  1626. $line->tva_tx = $objp->tva_tx;
  1627. $line->localtax1_tx = $objp->localtax1_tx;
  1628. $line->localtax2_tx = $objp->localtax2_tx;
  1629. $line->localtax1_type = $objp->localtax1_type;
  1630. $line->localtax2_type = $objp->localtax2_type;
  1631. $line->subprice = $objp->subprice;
  1632. $line->fk_remise_except = $objp->fk_remise_except;
  1633. $line->remise_percent = $objp->remise_percent;
  1634. $line->price = $objp->price; // TODO deprecated
  1635. $line->info_bits = $objp->info_bits;
  1636. $line->total_ht = $objp->total_ht;
  1637. $line->total_tva = $objp->total_tva;
  1638. $line->total_localtax1 = $objp->total_localtax1;
  1639. $line->total_localtax2 = $objp->total_localtax2;
  1640. $line->total_ttc = $objp->total_ttc;
  1641. $line->fk_fournprice = $objp->fk_fournprice;
  1642. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
  1643. $line->pa_ht = $marginInfos[0];
  1644. $line->marge_tx = $marginInfos[1];
  1645. $line->marque_tx = $marginInfos[2];
  1646. $line->special_code = $objp->special_code;
  1647. $line->rang = $objp->rang;
  1648. $line->fk_product = $objp->fk_product;
  1649. $line->ref = $objp->product_ref; // deprecated
  1650. $line->libelle = $objp->product_label; // deprecated
  1651. $line->product_ref = $objp->product_ref;
  1652. $line->product_label = $objp->product_label;
  1653. $line->product_desc = $objp->product_desc; // Description produit
  1654. $line->product_tobatch = $objp->product_tobatch;
  1655. $line->product_barcode = $objp->product_barcode;
  1656. $line->fk_product_type = $objp->fk_product_type; // deprecated
  1657. $line->fk_unit = $objp->fk_unit;
  1658. $line->weight = $objp->weight;
  1659. $line->weight_units = $objp->weight_units;
  1660. $line->volume = $objp->volume;
  1661. $line->volume_units = $objp->volume_units;
  1662. $line->date_start = $this->db->jdate($objp->date_start);
  1663. $line->date_end = $this->db->jdate($objp->date_end);
  1664. // Multicurrency
  1665. $line->fk_multicurrency = $objp->fk_multicurrency;
  1666. $line->multicurrency_code = $objp->multicurrency_code;
  1667. $line->multicurrency_subprice = $objp->multicurrency_subprice;
  1668. $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
  1669. $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
  1670. $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  1671. $line->fetch_optionals();
  1672. // multilangs
  1673. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
  1674. $tmpproduct = new Product($this->db);
  1675. $tmpproduct->fetch($objp->fk_product);
  1676. $tmpproduct->getMultiLangs();
  1677. $line->multilangs = $tmpproduct->multilangs;
  1678. }
  1679. $this->lines[$i] = $line;
  1680. $i++;
  1681. }
  1682. $this->db->free($result);
  1683. return $num;
  1684. } else {
  1685. $this->error = $this->db->lasterror();
  1686. return -3;
  1687. }
  1688. }
  1689. /**
  1690. * Set status to validated
  1691. *
  1692. * @param User $user Object user that validate
  1693. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  1694. * @return int <0 if KO, 0=Nothing done, >=0 if OK
  1695. */
  1696. public function valid($user, $notrigger = 0)
  1697. {
  1698. global $conf;
  1699. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1700. $error = 0;
  1701. // Protection
  1702. if ($this->statut == self::STATUS_VALIDATED) {
  1703. dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
  1704. return 0;
  1705. }
  1706. if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->creer))
  1707. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->propal_advance->validate)))) {
  1708. $this->error = 'ErrorPermissionDenied';
  1709. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  1710. return -1;
  1711. }
  1712. $now = dol_now();
  1713. $this->db->begin();
  1714. // Numbering module definition
  1715. $soc = new Societe($this->db);
  1716. $soc->fetch($this->socid);
  1717. // Define new ref
  1718. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  1719. $num = $this->getNextNumRef($soc);
  1720. } else {
  1721. $num = $this->ref;
  1722. }
  1723. $this->newref = dol_sanitizeFileName($num);
  1724. $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
  1725. $sql .= " SET ref = '".$this->db->escape($num)."',";
  1726. $sql .= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".((int) $user->id);
  1727. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
  1728. dol_syslog(get_class($this)."::valid", LOG_DEBUG);
  1729. $resql = $this->db->query($sql);
  1730. if (!$resql) {
  1731. dol_print_error($this->db);
  1732. $error++;
  1733. }
  1734. // Trigger calls
  1735. if (!$error && !$notrigger) {
  1736. // Call trigger
  1737. $result = $this->call_trigger('PROPAL_VALIDATE', $user);
  1738. if ($result < 0) {
  1739. $error++;
  1740. }
  1741. // End call triggers
  1742. }
  1743. if (!$error) {
  1744. $this->oldref = $this->ref;
  1745. // Rename directory if dir was a temporary ref
  1746. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  1747. // Now we rename also files into index
  1748. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'propale/".$this->db->escape($this->newref)."'";
  1749. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'propale/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
  1750. $resql = $this->db->query($sql);
  1751. if (!$resql) {
  1752. $error++;
  1753. $this->error = $this->db->lasterror();
  1754. }
  1755. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  1756. $oldref = dol_sanitizeFileName($this->ref);
  1757. $newref = dol_sanitizeFileName($num);
  1758. $dirsource = $conf->propal->multidir_output[$this->entity].'/'.$oldref;
  1759. $dirdest = $conf->propal->multidir_output[$this->entity].'/'.$newref;
  1760. if (!$error && file_exists($dirsource)) {
  1761. dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
  1762. if (@rename($dirsource, $dirdest)) {
  1763. dol_syslog("Rename ok");
  1764. // Rename docs starting with $oldref with $newref
  1765. $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/'));
  1766. foreach ($listoffiles as $fileentry) {
  1767. $dirsource = $fileentry['name'];
  1768. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  1769. $dirsource = $fileentry['path'].'/'.$dirsource;
  1770. $dirdest = $fileentry['path'].'/'.$dirdest;
  1771. @rename($dirsource, $dirdest);
  1772. }
  1773. }
  1774. }
  1775. }
  1776. $this->ref = $num;
  1777. $this->brouillon = 0;
  1778. $this->statut = self::STATUS_VALIDATED;
  1779. $this->user_valid_id = $user->id;
  1780. $this->datev = $now;
  1781. $this->db->commit();
  1782. return 1;
  1783. } else {
  1784. $this->db->rollback();
  1785. return -1;
  1786. }
  1787. }
  1788. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1789. /**
  1790. * Define proposal date
  1791. *
  1792. * @param User $user Object user that modify
  1793. * @param int $date Date
  1794. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1795. * @return int <0 if KO, >0 if OK
  1796. */
  1797. public function set_date($user, $date, $notrigger = 0)
  1798. {
  1799. // phpcs:enable
  1800. if (empty($date)) {
  1801. $this->error = 'ErrorBadParameter';
  1802. dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR);
  1803. return -1;
  1804. }
  1805. if (!empty($user->rights->propal->creer)) {
  1806. $error = 0;
  1807. $this->db->begin();
  1808. $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'";
  1809. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
  1810. dol_syslog(__METHOD__, LOG_DEBUG);
  1811. $resql = $this->db->query($sql);
  1812. if (!$resql) {
  1813. $this->errors[] = $this->db->error();
  1814. $error++;
  1815. }
  1816. if (!$error) {
  1817. $this->oldcopy = clone $this;
  1818. $this->date = $date;
  1819. $this->datep = $date; // deprecated
  1820. }
  1821. if (!$notrigger && empty($error)) {
  1822. // Call trigger
  1823. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  1824. if ($result < 0) {
  1825. $error++;
  1826. }
  1827. // End call triggers
  1828. }
  1829. if (!$error) {
  1830. $this->db->commit();
  1831. return 1;
  1832. } else {
  1833. foreach ($this->errors as $errmsg) {
  1834. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  1835. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1836. }
  1837. $this->db->rollback();
  1838. return -1 * $error;
  1839. }
  1840. }
  1841. }
  1842. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1843. /**
  1844. * Define end validity date
  1845. *
  1846. * @param User $user Object user that modify
  1847. * @param int $date_end_validity End of validity date
  1848. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1849. * @return int <0 if KO, >0 if OK
  1850. */
  1851. public function set_echeance($user, $date_end_validity, $notrigger = 0)
  1852. {
  1853. // phpcs:enable
  1854. if (!empty($user->rights->propal->creer)) {
  1855. $error = 0;
  1856. $this->db->begin();
  1857. $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_end_validity != '' ? "'".$this->db->idate($date_end_validity)."'" : 'null');
  1858. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".((int) self::STATUS_DRAFT);
  1859. dol_syslog(__METHOD__, LOG_DEBUG);
  1860. $resql = $this->db->query($sql);
  1861. if (!$resql) {
  1862. $this->errors[] = $this->db->error();
  1863. $error++;
  1864. }
  1865. if (!$error) {
  1866. $this->oldcopy = clone $this;
  1867. $this->fin_validite = $date_end_validity;
  1868. }
  1869. if (!$notrigger && empty($error)) {
  1870. // Call trigger
  1871. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  1872. if ($result < 0) {
  1873. $error++;
  1874. }
  1875. // End call triggers
  1876. }
  1877. if (!$error) {
  1878. $this->db->commit();
  1879. return 1;
  1880. } else {
  1881. foreach ($this->errors as $errmsg) {
  1882. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  1883. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1884. }
  1885. $this->db->rollback();
  1886. return -1 * $error;
  1887. }
  1888. }
  1889. }
  1890. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1891. /**
  1892. * Set delivery date
  1893. *
  1894. * @param User $user Object user that modify
  1895. * @param int $delivery_date Delivery date
  1896. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1897. * @return int <0 if ko, >0 if ok
  1898. * @deprecated Use setDeliveryDate
  1899. */
  1900. public function set_date_livraison($user, $delivery_date, $notrigger = 0)
  1901. {
  1902. // phpcs:enable
  1903. return $this->setDeliveryDate($user, $delivery_date, $notrigger);
  1904. }
  1905. /**
  1906. * Set delivery date
  1907. *
  1908. * @param User $user Object user that modify
  1909. * @param int $delivery_date Delivery date
  1910. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1911. * @return int <0 if ko, >0 if ok
  1912. */
  1913. public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
  1914. {
  1915. if (!empty($user->rights->propal->creer)) {
  1916. $error = 0;
  1917. $this->db->begin();
  1918. $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
  1919. $sql .= " SET date_livraison = ".($delivery_date != '' ? "'".$this->db->idate($delivery_date)."'" : 'null');
  1920. $sql .= " WHERE rowid = ".((int) $this->id);
  1921. dol_syslog(__METHOD__, LOG_DEBUG);
  1922. $resql = $this->db->query($sql);
  1923. if (!$resql) {
  1924. $this->errors[] = $this->db->error();
  1925. $error++;
  1926. }
  1927. if (!$error) {
  1928. $this->oldcopy = clone $this;
  1929. $this->date_livraison = $delivery_date;
  1930. $this->delivery_date = $delivery_date;
  1931. }
  1932. if (!$notrigger && empty($error)) {
  1933. // Call trigger
  1934. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  1935. if ($result < 0) {
  1936. $error++;
  1937. }
  1938. // End call triggers
  1939. }
  1940. if (!$error) {
  1941. $this->db->commit();
  1942. return 1;
  1943. } else {
  1944. foreach ($this->errors as $errmsg) {
  1945. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  1946. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1947. }
  1948. $this->db->rollback();
  1949. return -1 * $error;
  1950. }
  1951. }
  1952. }
  1953. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1954. /**
  1955. * Set delivery
  1956. *
  1957. * @param User $user Object user that modify
  1958. * @param int $id Availability id
  1959. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1960. * @return int <0 if KO, >0 if OK
  1961. */
  1962. public function set_availability($user, $id, $notrigger = 0)
  1963. {
  1964. // phpcs:enable
  1965. if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) {
  1966. $error = 0;
  1967. $this->db->begin();
  1968. $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
  1969. $sql .= " SET fk_availability = ".((int) $id);
  1970. $sql .= " WHERE rowid = ".((int) $this->id);
  1971. dol_syslog(__METHOD__.' availability('.$id.')', LOG_DEBUG);
  1972. $resql = $this->db->query($sql);
  1973. if (!$resql) {
  1974. $this->errors[] = $this->db->error();
  1975. $error++;
  1976. }
  1977. if (!$error) {
  1978. $this->oldcopy = clone $this;
  1979. $this->fk_availability = $id;
  1980. $this->availability_id = $id;
  1981. }
  1982. if (!$notrigger && empty($error)) {
  1983. // Call trigger
  1984. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  1985. if ($result < 0) {
  1986. $error++;
  1987. }
  1988. // End call triggers
  1989. }
  1990. if (!$error) {
  1991. $this->db->commit();
  1992. return 1;
  1993. } else {
  1994. foreach ($this->errors as $errmsg) {
  1995. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  1996. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1997. }
  1998. $this->db->rollback();
  1999. return -1 * $error;
  2000. }
  2001. } else {
  2002. $error_str = 'Propal status do not meet requirement '.$this->statut;
  2003. dol_syslog(__METHOD__.$error_str, LOG_ERR);
  2004. $this->error = $error_str;
  2005. $this->errors[] = $this->error;
  2006. return -2;
  2007. }
  2008. }
  2009. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2010. /**
  2011. * Set source of demand
  2012. *
  2013. * @param User $user Object user that modify
  2014. * @param int $id Input reason id
  2015. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2016. * @return int <0 if KO, >0 if OK
  2017. */
  2018. public function set_demand_reason($user, $id, $notrigger = 0)
  2019. {
  2020. // phpcs:enable
  2021. if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) {
  2022. $error = 0;
  2023. $this->db->begin();
  2024. $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
  2025. $sql .= " SET fk_input_reason = ".((int) $id);
  2026. $sql .= " WHERE rowid = ".((int) $this->id);
  2027. dol_syslog(__METHOD__, LOG_DEBUG);
  2028. $resql = $this->db->query($sql);
  2029. if (!$resql) {
  2030. $this->errors[] = $this->db->error();
  2031. $error++;
  2032. }
  2033. if (!$error) {
  2034. $this->oldcopy = clone $this;
  2035. $this->fk_input_reason = $id;
  2036. $this->demand_reason_id = $id;
  2037. }
  2038. if (!$notrigger && empty($error)) {
  2039. // Call trigger
  2040. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  2041. if ($result < 0) {
  2042. $error++;
  2043. }
  2044. // End call triggers
  2045. }
  2046. if (!$error) {
  2047. $this->db->commit();
  2048. return 1;
  2049. } else {
  2050. foreach ($this->errors as $errmsg) {
  2051. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2052. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2053. }
  2054. $this->db->rollback();
  2055. return -1 * $error;
  2056. }
  2057. } else {
  2058. $error_str = 'Propal status do not meet requirement '.$this->statut;
  2059. dol_syslog(__METHOD__.$error_str, LOG_ERR);
  2060. $this->error = $error_str;
  2061. $this->errors[] = $this->error;
  2062. return -2;
  2063. }
  2064. }
  2065. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2066. /**
  2067. * Set customer reference number
  2068. *
  2069. * @param User $user Object user that modify
  2070. * @param string $ref_client Customer reference
  2071. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2072. * @return int <0 if ko, >0 if ok
  2073. */
  2074. public function set_ref_client($user, $ref_client, $notrigger = 0)
  2075. {
  2076. // phpcs:enable
  2077. if (!empty($user->rights->propal->creer)) {
  2078. $error = 0;
  2079. $this->db->begin();
  2080. $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET ref_client = ".(empty($ref_client) ? 'NULL' : "'".$this->db->escape($ref_client)."'");
  2081. $sql .= " WHERE rowid = ".((int) $this->id);
  2082. dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
  2083. $resql = $this->db->query($sql);
  2084. if (!$resql) {
  2085. $this->errors[] = $this->db->error();
  2086. $error++;
  2087. }
  2088. if (!$error) {
  2089. $this->oldcopy = clone $this;
  2090. $this->ref_client = $ref_client;
  2091. }
  2092. if (!$notrigger && empty($error)) {
  2093. // Call trigger
  2094. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  2095. if ($result < 0) {
  2096. $error++;
  2097. }
  2098. // End call triggers
  2099. }
  2100. if (!$error) {
  2101. $this->db->commit();
  2102. return 1;
  2103. } else {
  2104. foreach ($this->errors as $errmsg) {
  2105. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2106. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2107. }
  2108. $this->db->rollback();
  2109. return -1 * $error;
  2110. }
  2111. } else {
  2112. return -1;
  2113. }
  2114. }
  2115. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2116. /**
  2117. * Set an overall discount on the proposal
  2118. *
  2119. * @param User $user Object user that modify
  2120. * @param double $remise Amount discount
  2121. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2122. * @return int <0 if ko, >0 if ok
  2123. */
  2124. public function set_remise_percent($user, $remise, $notrigger = 0)
  2125. {
  2126. // phpcs:enable
  2127. $remise = trim($remise) ?trim($remise) : 0;
  2128. if (!empty($user->rights->propal->creer)) {
  2129. $remise = price2num($remise, 2);
  2130. $error = 0;
  2131. $this->db->begin();
  2132. $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".((float) $remise);
  2133. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
  2134. dol_syslog(__METHOD__, LOG_DEBUG);
  2135. $resql = $this->db->query($sql);
  2136. if (!$resql) {
  2137. $this->errors[] = $this->db->error();
  2138. $error++;
  2139. }
  2140. if (!$error) {
  2141. $this->oldcopy = clone $this;
  2142. $this->remise_percent = $remise;
  2143. $this->update_price(1);
  2144. }
  2145. if (!$notrigger && empty($error)) {
  2146. // Call trigger
  2147. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  2148. if ($result < 0) {
  2149. $error++;
  2150. }
  2151. // End call triggers
  2152. }
  2153. if (!$error) {
  2154. $this->db->commit();
  2155. return 1;
  2156. } else {
  2157. foreach ($this->errors as $errmsg) {
  2158. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2159. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2160. }
  2161. $this->db->rollback();
  2162. return -1 * $error;
  2163. }
  2164. }
  2165. }
  2166. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2167. /**
  2168. * Set an absolute overall discount on the proposal
  2169. *
  2170. * @param User $user Object user that modify
  2171. * @param double $remise Amount discount
  2172. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2173. * @return int <0 if ko, >0 if ok
  2174. */
  2175. public function set_remise_absolue($user, $remise, $notrigger = 0)
  2176. {
  2177. // phpcs:enable
  2178. if (empty($remise)) {
  2179. $remise = 0;
  2180. }
  2181. $remise = price2num($remise);
  2182. if (!empty($user->rights->propal->creer)) {
  2183. $error = 0;
  2184. $this->db->begin();
  2185. $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
  2186. $sql .= " SET remise_absolue = ".((float) $remise);
  2187. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
  2188. dol_syslog(__METHOD__, LOG_DEBUG);
  2189. $resql = $this->db->query($sql);
  2190. if (!$resql) {
  2191. $this->errors[] = $this->db->error();
  2192. $error++;
  2193. }
  2194. if (!$error) {
  2195. $this->oldcopy = clone $this;
  2196. $this->update_price(1);
  2197. }
  2198. if (!$notrigger && empty($error)) {
  2199. // Call trigger
  2200. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  2201. if ($result < 0) {
  2202. $error++;
  2203. }
  2204. // End call triggers
  2205. }
  2206. if (!$error) {
  2207. $this->db->commit();
  2208. return 1;
  2209. } else {
  2210. foreach ($this->errors as $errmsg) {
  2211. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2212. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2213. }
  2214. $this->db->rollback();
  2215. return -1 * $error;
  2216. }
  2217. }
  2218. }
  2219. /**
  2220. * Reopen the commercial proposal
  2221. *
  2222. * @param User $user Object user that close
  2223. * @param int $status Status
  2224. * @param string $note Comment
  2225. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2226. * @return int <0 if KO, >0 if OK
  2227. */
  2228. public function reopen($user, $status, $note = '', $notrigger = 0)
  2229. {
  2230. $error = 0;
  2231. $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
  2232. $sql .= " SET fk_statut = ".((int) $status).",";
  2233. if (!empty($note)) {
  2234. $sql .= " note_private = '".$this->db->escape($note)."',";
  2235. }
  2236. $sql .= " date_cloture=NULL, fk_user_cloture=NULL";
  2237. $sql .= " WHERE rowid = ".((int) $this->id);
  2238. $this->db->begin();
  2239. dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
  2240. $resql = $this->db->query($sql);
  2241. if (!$resql) {
  2242. $error++;
  2243. $this->errors[] = "Error ".$this->db->lasterror();
  2244. }
  2245. if (!$error) {
  2246. if (!$notrigger) {
  2247. // Call trigger
  2248. $result = $this->call_trigger('PROPAL_REOPEN', $user);
  2249. if ($result < 0) {
  2250. $error++;
  2251. }
  2252. // End call triggers
  2253. }
  2254. }
  2255. // Commit or rollback
  2256. if ($error) {
  2257. if (!empty($this->errors)) {
  2258. foreach ($this->errors as $errmsg) {
  2259. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  2260. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2261. }
  2262. }
  2263. $this->db->rollback();
  2264. return -1 * $error;
  2265. } else {
  2266. $this->statut = $status;
  2267. $this->status = $status;
  2268. $this->db->commit();
  2269. return 1;
  2270. }
  2271. }
  2272. /**
  2273. * Close/set the commercial proposal to status signed or refused (fill also date signature)
  2274. *
  2275. * @param User $user Object user that close
  2276. * @param int $status Status (self::STATUS_BILLED or self::STATUS_REFUSED)
  2277. * @param string $note Complete private note with this note
  2278. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  2279. * @return int <0 if KO, >0 if OK
  2280. */
  2281. public function closeProposal($user, $status, $note = '', $notrigger = 0)
  2282. {
  2283. global $langs,$conf;
  2284. $error = 0;
  2285. $now = dol_now();
  2286. $this->db->begin();
  2287. $newprivatenote = dol_concatdesc($this->note_private, $note);
  2288. if (empty($conf->global->PROPALE_KEEP_OLD_SIGNATURE_INFO)) {
  2289. $date_signature = $now;
  2290. $fk_user_signature = $user->id;
  2291. } else {
  2292. $this->info($this->id);
  2293. if (!isset($this->date_signature) || $this->date_signature == '') {
  2294. $date_signature = $now;
  2295. $fk_user_signature = $user->id;
  2296. } else {
  2297. $date_signature = $this->date_signature;
  2298. $fk_user_signature = $this->user_signature->id;
  2299. }
  2300. }
  2301. $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
  2302. $sql .= " SET fk_statut = ".((int) $status).", note_private = '".$this->db->escape($newprivatenote)."', date_signature='".$this->db->idate($date_signature)."', fk_user_signature=".$fk_user_signature;
  2303. $sql .= " WHERE rowid = ".((int) $this->id);
  2304. $resql = $this->db->query($sql);
  2305. if ($resql) {
  2306. // Status self::STATUS_REFUSED by default
  2307. $modelpdf = !empty($conf->global->PROPALE_ADDON_PDF_ODT_CLOSED) ? $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED : $this->model_pdf;
  2308. $trigger_name = 'PROPAL_CLOSE_REFUSED'; // used later in call_trigger()
  2309. if ($status == self::STATUS_SIGNED) { // Status self::STATUS_SIGNED
  2310. $trigger_name = 'PROPAL_CLOSE_SIGNED'; // used later in call_trigger()
  2311. $modelpdf = !empty($conf->global->PROPALE_ADDON_PDF_ODT_TOBILL) ? $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL : $this->model_pdf;
  2312. // The connected company is classified as a client
  2313. $soc=new Societe($this->db);
  2314. $soc->id = $this->socid;
  2315. $result = $soc->set_as_client();
  2316. if ($result < 0) {
  2317. $this->error=$this->db->lasterror();
  2318. $this->db->rollback();
  2319. return -2;
  2320. }
  2321. }
  2322. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  2323. // Define output language
  2324. $outputlangs = $langs;
  2325. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2326. $outputlangs = new Translate("", $conf);
  2327. $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
  2328. $outputlangs->setDefaultLang($newlang);
  2329. }
  2330. // PDF
  2331. $hidedetails = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
  2332. $hidedesc = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
  2333. $hideref = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
  2334. //$ret=$object->fetch($id); // Reload to get new records
  2335. $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  2336. }
  2337. if (!$error) {
  2338. $this->oldcopy= clone $this;
  2339. $this->statut = $status;
  2340. $this->status = $status;
  2341. $this->date_signature = $date_signature;
  2342. $this->note_private = $newprivatenote;
  2343. }
  2344. if (!$notrigger && empty($error)) {
  2345. // Call trigger
  2346. $result=$this->call_trigger($trigger_name, $user);
  2347. if ($result < 0) {
  2348. $error++;
  2349. }
  2350. // End call triggers
  2351. }
  2352. if (!$error ) {
  2353. $this->db->commit();
  2354. return 1;
  2355. } else {
  2356. $this->statut = $this->oldcopy->statut;
  2357. $this->status = $this->oldcopy->statut;
  2358. $this->date_signature = $this->oldcopy->date_signature;
  2359. $this->note_private = $this->oldcopy->note_private;
  2360. $this->db->rollback();
  2361. return -1;
  2362. }
  2363. } else {
  2364. $this->error = $this->db->lasterror();
  2365. $this->db->rollback();
  2366. return -1;
  2367. }
  2368. }
  2369. /**
  2370. * Classify the proposal to status Billed
  2371. *
  2372. * @param User $user Object user
  2373. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2374. * @param string $note Complete private note with this note
  2375. * @return int <0 if KO, 0 = nothing done, >0 if OK
  2376. */
  2377. public function classifyBilled(User $user, $notrigger = 0, $note = '')
  2378. {
  2379. global $conf, $langs;
  2380. $error = 0;
  2381. $now = dol_now();
  2382. $num = 0;
  2383. $triggerName = 'PROPAL_CLASSIFY_BILLED';
  2384. $this->db->begin();
  2385. $newprivatenote = dol_concatdesc($this->note_private, $note);
  2386. $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET fk_statut = '.self::STATUS_BILLED.", ";
  2387. $sql .= " note_private = '".$this->db->escape($newprivatenote)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".((int) $user->id);
  2388. $sql .= ' WHERE rowid = '.((int) $this->id).' AND fk_statut = '.((int) self::STATUS_SIGNED);
  2389. dol_syslog(__METHOD__, LOG_DEBUG);
  2390. $resql = $this->db->query($sql);
  2391. if (!$resql) {
  2392. $this->errors[] = $this->db->error();
  2393. $error++;
  2394. } else {
  2395. $num = $this->db->affected_rows($resql);
  2396. }
  2397. if (!$error) {
  2398. $modelpdf = $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED ? $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED : $this->model_pdf;
  2399. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  2400. // Define output language
  2401. $outputlangs = $langs;
  2402. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2403. $outputlangs = new Translate("", $conf);
  2404. $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
  2405. $outputlangs->setDefaultLang($newlang);
  2406. }
  2407. // PDF
  2408. $hidedetails = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
  2409. $hidedesc = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
  2410. $hideref = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
  2411. //$ret=$object->fetch($id); // Reload to get new records
  2412. $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  2413. }
  2414. $this->oldcopy = clone $this;
  2415. $this->statut = self::STATUS_BILLED;
  2416. $this->date_cloture = $now;
  2417. $this->note_private = $newprivatenote;
  2418. }
  2419. if (!$notrigger && empty($error)) {
  2420. // Call trigger
  2421. $result = $this->call_trigger($triggerName, $user);
  2422. if ($result < 0) {
  2423. $error++;
  2424. }
  2425. // End call triggers
  2426. }
  2427. if (!$error) {
  2428. $this->db->commit();
  2429. return $num;
  2430. } else {
  2431. foreach ($this->errors as $errmsg) {
  2432. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2433. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2434. }
  2435. $this->db->rollback();
  2436. return -1 * $error;
  2437. }
  2438. }
  2439. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2440. /**
  2441. * Set draft status
  2442. *
  2443. * @param User $user Object user that modify
  2444. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2445. * @return int <0 if KO, >0 if OK
  2446. */
  2447. public function setDraft($user, $notrigger = 0)
  2448. {
  2449. // phpcs:enable
  2450. $error = 0;
  2451. // Protection
  2452. if ($this->statut <= self::STATUS_DRAFT) {
  2453. return 0;
  2454. }
  2455. dol_syslog(get_class($this)."::setDraft", LOG_DEBUG);
  2456. $this->db->begin();
  2457. $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
  2458. $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
  2459. $sql .= ", online_sign_ip = NULL , online_sign_name = NULL";
  2460. $sql .= " WHERE rowid = ".((int) $this->id);
  2461. $resql = $this->db->query($sql);
  2462. if (!$resql) {
  2463. $this->errors[] = $this->db->error();
  2464. $error++;
  2465. }
  2466. if (!$error) {
  2467. $this->oldcopy = clone $this;
  2468. }
  2469. if (!$notrigger && empty($error)) {
  2470. // Call trigger
  2471. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  2472. if ($result < 0) {
  2473. $error++;
  2474. }
  2475. // End call triggers
  2476. }
  2477. if (!$error) {
  2478. $this->statut = self::STATUS_DRAFT;
  2479. $this->brouillon = 1;
  2480. $this->db->commit();
  2481. return 1;
  2482. } else {
  2483. foreach ($this->errors as $errmsg) {
  2484. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2485. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2486. }
  2487. $this->db->rollback();
  2488. return -1 * $error;
  2489. }
  2490. }
  2491. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2492. /**
  2493. * Return list of proposal (eventually filtered on user) into an array
  2494. *
  2495. * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
  2496. * @param int $draft 0=not draft, 1=draft
  2497. * @param int $notcurrentuser 0=all user, 1=not current user
  2498. * @param int $socid Id third pary
  2499. * @param int $limit For pagination
  2500. * @param int $offset For pagination
  2501. * @param string $sortfield Sort criteria
  2502. * @param string $sortorder Sort order
  2503. * @return int -1 if KO, array with result if OK
  2504. */
  2505. public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datep', $sortorder = 'DESC')
  2506. {
  2507. // phpcs:enable
  2508. global $user;
  2509. $ga = array();
  2510. $sql = "SELECT s.rowid, s.nom as name, s.client,";
  2511. $sql .= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
  2512. $sql .= " p.datep as dp, p.fin_validite as datelimite";
  2513. if (empty($user->rights->societe->client->voir) && !$socid) {
  2514. $sql .= ", sc.fk_soc, sc.fk_user";
  2515. }
  2516. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c";
  2517. if (empty($user->rights->societe->client->voir) && !$socid) {
  2518. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  2519. }
  2520. $sql .= " WHERE p.entity IN (".getEntity('propal').")";
  2521. $sql .= " AND p.fk_soc = s.rowid";
  2522. $sql .= " AND p.fk_statut = c.id";
  2523. if (empty($user->rights->societe->client->voir) && !$socid) { //restriction
  2524. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2525. }
  2526. if ($socid) {
  2527. $sql .= " AND s.rowid = ".((int) $socid);
  2528. }
  2529. if ($draft) {
  2530. $sql .= " AND p.fk_statut = ".self::STATUS_DRAFT;
  2531. }
  2532. if ($notcurrentuser > 0) {
  2533. $sql .= " AND p.fk_user_author <> ".((int) $user->id);
  2534. }
  2535. $sql .= $this->db->order($sortfield, $sortorder);
  2536. $sql .= $this->db->plimit($limit, $offset);
  2537. $result = $this->db->query($sql);
  2538. if ($result) {
  2539. $num = $this->db->num_rows($result);
  2540. if ($num) {
  2541. $i = 0;
  2542. while ($i < $num) {
  2543. $obj = $this->db->fetch_object($result);
  2544. if ($shortlist == 1) {
  2545. $ga[$obj->propalid] = $obj->ref;
  2546. } elseif ($shortlist == 2) {
  2547. $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')';
  2548. } else {
  2549. $ga[$i]['id'] = $obj->propalid;
  2550. $ga[$i]['ref'] = $obj->ref;
  2551. $ga[$i]['name'] = $obj->name;
  2552. }
  2553. $i++;
  2554. }
  2555. }
  2556. return $ga;
  2557. } else {
  2558. dol_print_error($this->db);
  2559. return -1;
  2560. }
  2561. }
  2562. /**
  2563. * Returns an array with the numbers of related invoices
  2564. *
  2565. * @return array Array of invoices
  2566. */
  2567. public function getInvoiceArrayList()
  2568. {
  2569. return $this->InvoiceArrayList($this->id);
  2570. }
  2571. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2572. /**
  2573. * Returns an array with id and ref of related invoices
  2574. *
  2575. * @param int $id Id propal
  2576. * @return array Array of invoices id
  2577. */
  2578. public function InvoiceArrayList($id)
  2579. {
  2580. // phpcs:enable
  2581. $ga = array();
  2582. $linkedInvoices = array();
  2583. $this->fetchObjectLinked($id, $this->element);
  2584. foreach ($this->linkedObjectsIds as $objecttype => $objectid) {
  2585. // Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n
  2586. // On parcourt donc une liste d'objets en tant qu'objet unique
  2587. foreach ($objectid as $key => $object) {
  2588. // Cas des factures liees directement
  2589. if ($objecttype == 'facture') {
  2590. $linkedInvoices[] = $object;
  2591. } else {
  2592. // Cas des factures liees par un autre objet (ex: commande)
  2593. $this->fetchObjectLinked($object, $objecttype);
  2594. foreach ($this->linkedObjectsIds as $subobjecttype => $subobjectid) {
  2595. foreach ($subobjectid as $subkey => $subobject) {
  2596. if ($subobjecttype == 'facture') {
  2597. $linkedInvoices[] = $subobject;
  2598. }
  2599. }
  2600. }
  2601. }
  2602. }
  2603. }
  2604. if (count($linkedInvoices) > 0) {
  2605. $sql = "SELECT rowid as facid, ref, total_ht as total, datef as df, fk_user_author, fk_statut, paye";
  2606. $sql .= " FROM ".MAIN_DB_PREFIX."facture";
  2607. $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $linkedInvoices)).")";
  2608. dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG);
  2609. $resql = $this->db->query($sql);
  2610. if ($resql) {
  2611. $tab_sqlobj = array();
  2612. $nump = $this->db->num_rows($resql);
  2613. for ($i = 0; $i < $nump; $i++) {
  2614. $sqlobj = $this->db->fetch_object($resql);
  2615. $tab_sqlobj[] = $sqlobj;
  2616. }
  2617. $this->db->free($resql);
  2618. $nump = count($tab_sqlobj);
  2619. if ($nump) {
  2620. $i = 0;
  2621. while ($i < $nump) {
  2622. $obj = array_shift($tab_sqlobj);
  2623. $ga[$i] = $obj;
  2624. $i++;
  2625. }
  2626. }
  2627. return $ga;
  2628. } else {
  2629. return -1;
  2630. }
  2631. } else {
  2632. return $ga;
  2633. }
  2634. }
  2635. /**
  2636. * Delete proposal
  2637. *
  2638. * @param User $user Object user that delete
  2639. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2640. * @return int >0 if OK, <=0 if KO
  2641. */
  2642. public function delete($user, $notrigger = 0)
  2643. {
  2644. global $conf;
  2645. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2646. $error = 0;
  2647. $this->db->begin();
  2648. if (!$notrigger) {
  2649. // Call trigger
  2650. $result = $this->call_trigger('PROPAL_DELETE', $user);
  2651. if ($result < 0) {
  2652. $error++;
  2653. }
  2654. // End call triggers
  2655. }
  2656. // Delete extrafields of lines and lines
  2657. if (!$error && !empty($this->table_element_line)) {
  2658. $tabletodelete = $this->table_element_line;
  2659. $sqlef = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete."_extrafields WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id).")";
  2660. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
  2661. if (!$this->db->query($sqlef) || !$this->db->query($sql)) {
  2662. $error++;
  2663. $this->error = $this->db->lasterror();
  2664. $this->errors[] = $this->error;
  2665. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  2666. }
  2667. }
  2668. if (!$error) {
  2669. // Delete linked object
  2670. $res = $this->deleteObjectLinked();
  2671. if ($res < 0) {
  2672. $error++;
  2673. }
  2674. }
  2675. if (!$error) {
  2676. // Delete linked contacts
  2677. $res = $this->delete_linked_contact();
  2678. if ($res < 0) {
  2679. $error++;
  2680. }
  2681. }
  2682. // Removed extrafields of object
  2683. if (!$error) {
  2684. $result = $this->deleteExtraFields();
  2685. if ($result < 0) {
  2686. $error++;
  2687. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  2688. }
  2689. }
  2690. // Delete main record
  2691. if (!$error) {
  2692. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
  2693. $res = $this->db->query($sql);
  2694. if (!$res) {
  2695. $error++;
  2696. $this->error = $this->db->lasterror();
  2697. $this->errors[] = $this->error;
  2698. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  2699. }
  2700. }
  2701. // Delete record into ECM index and physically
  2702. if (!$error) {
  2703. $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
  2704. if (!$res) {
  2705. $error++;
  2706. }
  2707. }
  2708. if (!$error) {
  2709. // We remove directory
  2710. $ref = dol_sanitizeFileName($this->ref);
  2711. if ($conf->propal->multidir_output[$this->entity] && !empty($this->ref)) {
  2712. $dir = $conf->propal->multidir_output[$this->entity]."/".$ref;
  2713. $file = $dir."/".$ref.".pdf";
  2714. if (file_exists($file)) {
  2715. dol_delete_preview($this);
  2716. if (!dol_delete_file($file, 0, 0, 0, $this)) {
  2717. $this->error = 'ErrorFailToDeleteFile';
  2718. $this->errors[] = $this->error;
  2719. $this->db->rollback();
  2720. return 0;
  2721. }
  2722. }
  2723. if (file_exists($dir)) {
  2724. $res = @dol_delete_dir_recursive($dir);
  2725. if (!$res) {
  2726. $this->error = 'ErrorFailToDeleteDir';
  2727. $this->errors[] = $this->error;
  2728. $this->db->rollback();
  2729. return 0;
  2730. }
  2731. }
  2732. }
  2733. }
  2734. if (!$error) {
  2735. dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
  2736. $this->db->commit();
  2737. return 1;
  2738. } else {
  2739. $this->db->rollback();
  2740. return -1;
  2741. }
  2742. }
  2743. /**
  2744. * Change the delivery time
  2745. *
  2746. * @param int $availability_id Id of new delivery time
  2747. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2748. * @return int >0 if OK, <0 if KO
  2749. * @deprecated use set_availability
  2750. */
  2751. public function availability($availability_id, $notrigger = 0)
  2752. {
  2753. global $user;
  2754. if ($this->statut >= self::STATUS_DRAFT) {
  2755. $error = 0;
  2756. $this->db->begin();
  2757. $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal';
  2758. $sql .= ' SET fk_availability = '.((int) $availability_id);
  2759. $sql .= ' WHERE rowid='.((int) $this->id);
  2760. dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
  2761. $resql = $this->db->query($sql);
  2762. if (!$resql) {
  2763. $this->errors[] = $this->db->error();
  2764. $error++;
  2765. }
  2766. if (!$error) {
  2767. $this->oldcopy = clone $this;
  2768. $this->availability_id = $availability_id;
  2769. }
  2770. if (!$notrigger && empty($error)) {
  2771. // Call trigger
  2772. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  2773. if ($result < 0) {
  2774. $error++;
  2775. }
  2776. // End call triggers
  2777. }
  2778. if (!$error) {
  2779. $this->db->commit();
  2780. return 1;
  2781. } else {
  2782. foreach ($this->errors as $errmsg) {
  2783. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2784. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2785. }
  2786. $this->db->rollback();
  2787. return -1 * $error;
  2788. }
  2789. } else {
  2790. $error_str = 'Propal status do not meet requirement '.$this->statut;
  2791. dol_syslog(__METHOD__.$error_str, LOG_ERR);
  2792. $this->error = $error_str;
  2793. $this->errors[] = $this->error;
  2794. return -2;
  2795. }
  2796. }
  2797. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2798. /**
  2799. * Change source demand
  2800. *
  2801. * @param int $demand_reason_id Id of new source demand
  2802. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2803. * @return int >0 si ok, <0 si ko
  2804. * @deprecated use set_demand_reason
  2805. */
  2806. public function demand_reason($demand_reason_id, $notrigger = 0)
  2807. {
  2808. // phpcs:enable
  2809. global $user;
  2810. if ($this->statut >= self::STATUS_DRAFT) {
  2811. $error = 0;
  2812. $this->db->begin();
  2813. $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal';
  2814. $sql .= ' SET fk_input_reason = '.((int) $demand_reason_id);
  2815. $sql .= ' WHERE rowid='.((int) $this->id);
  2816. dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG);
  2817. $resql = $this->db->query($sql);
  2818. if (!$resql) {
  2819. $this->errors[] = $this->db->error();
  2820. $error++;
  2821. }
  2822. if (!$error) {
  2823. $this->oldcopy = clone $this;
  2824. $this->demand_reason_id = $demand_reason_id;
  2825. }
  2826. if (!$notrigger && empty($error)) {
  2827. // Call trigger
  2828. $result = $this->call_trigger('PROPAL_MODIFY', $user);
  2829. if ($result < 0) {
  2830. $error++;
  2831. }
  2832. // End call triggers
  2833. }
  2834. if (!$error) {
  2835. $this->db->commit();
  2836. return 1;
  2837. } else {
  2838. foreach ($this->errors as $errmsg) {
  2839. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2840. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2841. }
  2842. $this->db->rollback();
  2843. return -1 * $error;
  2844. }
  2845. } else {
  2846. $error_str = 'Propal status do not meet requirement '.$this->statut;
  2847. dol_syslog(__METHOD__.$error_str, LOG_ERR);
  2848. $this->error = $error_str;
  2849. $this->errors[] = $this->error;
  2850. return -2;
  2851. }
  2852. }
  2853. /**
  2854. * Object Proposal Information
  2855. *
  2856. * @param int $id Proposal id
  2857. * @return void
  2858. */
  2859. public function info($id)
  2860. {
  2861. $sql = "SELECT c.rowid, ";
  2862. $sql .= " c.datec, c.date_valid as datev, c.date_signature, c.date_cloture,";
  2863. $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_signature, c.fk_user_cloture";
  2864. $sql .= " FROM ".MAIN_DB_PREFIX."propal as c";
  2865. $sql .= " WHERE c.rowid = ".((int) $id);
  2866. $result = $this->db->query($sql);
  2867. if ($result) {
  2868. if ($this->db->num_rows($result)) {
  2869. $obj = $this->db->fetch_object($result);
  2870. $this->id = $obj->rowid;
  2871. $this->date_creation = $this->db->jdate($obj->datec);
  2872. $this->date_validation = $this->db->jdate($obj->datev);
  2873. $this->date_signature = $this->db->jdate($obj->date_signature);
  2874. $this->date_cloture = $this->db->jdate($obj->date_cloture);
  2875. $cuser = new User($this->db);
  2876. $cuser->fetch($obj->fk_user_author);
  2877. $this->user_creation = $cuser;
  2878. if ($obj->fk_user_valid) {
  2879. $vuser = new User($this->db);
  2880. $vuser->fetch($obj->fk_user_valid);
  2881. $this->user_validation = $vuser;
  2882. }
  2883. if ($obj->fk_user_signature) {
  2884. $user_signature = new User($this->db);
  2885. $user_signature->fetch($obj->fk_user_signature);
  2886. $this->user_signature = $user_signature;
  2887. }
  2888. if ($obj->fk_user_cloture) {
  2889. $cluser = new User($this->db);
  2890. $cluser->fetch($obj->fk_user_cloture);
  2891. $this->user_cloture = $cluser;
  2892. }
  2893. }
  2894. $this->db->free($result);
  2895. } else {
  2896. dol_print_error($this->db);
  2897. }
  2898. }
  2899. /**
  2900. * Return label of status of proposal (draft, validated, ...)
  2901. *
  2902. * @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
  2903. * @return string Label
  2904. */
  2905. public function getLibStatut($mode = 0)
  2906. {
  2907. return $this->LibStatut($this->statut, $mode);
  2908. }
  2909. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2910. /**
  2911. * Return label of a status (draft, validated, ...)
  2912. *
  2913. * @param int $status Id status
  2914. * @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
  2915. * @return string Label
  2916. */
  2917. public function LibStatut($status, $mode = 1)
  2918. {
  2919. // phpcs:enable
  2920. global $conf, $hookmanager;
  2921. // Init/load array of translation of status
  2922. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  2923. global $langs;
  2924. $langs->load("propal");
  2925. $this->labelStatus[0] = $langs->transnoentitiesnoconv("PropalStatusDraft");
  2926. $this->labelStatus[1] = $langs->transnoentitiesnoconv("PropalStatusValidated");
  2927. $this->labelStatus[2] = $langs->transnoentitiesnoconv("PropalStatusSigned");
  2928. $this->labelStatus[3] = $langs->transnoentitiesnoconv("PropalStatusNotSigned");
  2929. $this->labelStatus[4] = $langs->transnoentitiesnoconv("PropalStatusBilled");
  2930. $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("PropalStatusDraftShort");
  2931. $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("PropalStatusValidatedShort");
  2932. $this->labelStatusShort[2] = $langs->transnoentitiesnoconv("PropalStatusSignedShort");
  2933. $this->labelStatusShort[3] = $langs->transnoentitiesnoconv("PropalStatusNotSignedShort");
  2934. $this->labelStatusShort[4] = $langs->transnoentitiesnoconv("PropalStatusBilledShort");
  2935. }
  2936. $statusType = '';
  2937. if ($status == self::STATUS_DRAFT) {
  2938. $statusType = 'status0';
  2939. } elseif ($status == self::STATUS_VALIDATED) {
  2940. $statusType = 'status1';
  2941. } elseif ($status == self::STATUS_SIGNED) {
  2942. $statusType = 'status4';
  2943. } elseif ($status == self::STATUS_NOTSIGNED) {
  2944. $statusType = 'status9';
  2945. } elseif ($status == self::STATUS_BILLED) {
  2946. $statusType = 'status6';
  2947. }
  2948. $parameters = array('status' => $status, 'mode' => $mode);
  2949. $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
  2950. if ($reshook > 0) {
  2951. return $hookmanager->resPrint;
  2952. }
  2953. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  2954. }
  2955. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2956. /**
  2957. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  2958. *
  2959. * @param User $user Object user
  2960. * @param int $mode "opened" for proposal to close, "signed" for proposal to invoice
  2961. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  2962. */
  2963. public function load_board($user, $mode)
  2964. {
  2965. // phpcs:enable
  2966. global $conf, $langs;
  2967. $clause = " WHERE";
  2968. $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin, p.total_ht";
  2969. $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
  2970. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  2971. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
  2972. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  2973. $clause = " AND";
  2974. }
  2975. $sql .= $clause." p.entity IN (".getEntity('propal').")";
  2976. if ($mode == 'opened') {
  2977. $sql .= " AND p.fk_statut = ".self::STATUS_VALIDATED;
  2978. }
  2979. if ($mode == 'signed') {
  2980. $sql .= " AND p.fk_statut = ".self::STATUS_SIGNED;
  2981. }
  2982. if ($user->socid) {
  2983. $sql .= " AND p.fk_soc = ".((int) $user->socid);
  2984. }
  2985. $resql = $this->db->query($sql);
  2986. if ($resql) {
  2987. $langs->load("propal");
  2988. $now = dol_now();
  2989. $delay_warning = 0;
  2990. $status = 0;
  2991. $label = $labelShort = '';
  2992. if ($mode == 'opened') {
  2993. $delay_warning = $conf->propal->cloture->warning_delay;
  2994. $status = self::STATUS_VALIDATED;
  2995. $label = $langs->transnoentitiesnoconv("PropalsToClose");
  2996. $labelShort = $langs->transnoentitiesnoconv("ToAcceptRefuse");
  2997. }
  2998. if ($mode == 'signed') {
  2999. $delay_warning = $conf->propal->facturation->warning_delay;
  3000. $status = self::STATUS_SIGNED;
  3001. $label = $langs->trans("PropalsToBill"); // We set here bill but may be billed or ordered
  3002. $labelShort = $langs->trans("ToBill");
  3003. }
  3004. $response = new WorkboardResponse();
  3005. $response->warning_delay = $delay_warning / 60 / 60 / 24;
  3006. $response->label = $label;
  3007. $response->labelShort = $labelShort;
  3008. $response->url = DOL_URL_ROOT.'/comm/propal/list.php?search_status='.$status.'&mainmenu=commercial&leftmenu=propals';
  3009. $response->url_late = DOL_URL_ROOT.'/comm/propal/list.php?search_status='.$status.'&mainmenu=commercial&leftmenu=propals&sortfield=p.datep&sortorder=asc';
  3010. $response->img = img_object('', "propal");
  3011. // This assignment in condition is not a bug. It allows walking the results.
  3012. while ($obj = $this->db->fetch_object($resql)) {
  3013. $response->nbtodo++;
  3014. $response->total += $obj->total_ht;
  3015. if ($mode == 'opened') {
  3016. $datelimit = $this->db->jdate($obj->datefin);
  3017. if ($datelimit < ($now - $delay_warning)) {
  3018. $response->nbtodolate++;
  3019. }
  3020. }
  3021. // TODO Definir regle des propales a facturer en retard
  3022. // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++;
  3023. }
  3024. return $response;
  3025. } else {
  3026. $this->error = $this->db->error();
  3027. return -1;
  3028. }
  3029. }
  3030. /**
  3031. * Initialise an instance with random values.
  3032. * Used to build previews or test instances.
  3033. * id must be 0 if object instance is a specimen.
  3034. *
  3035. * @return void
  3036. */
  3037. public function initAsSpecimen()
  3038. {
  3039. global $conf, $langs;
  3040. // Load array of products prodids
  3041. $num_prods = 0;
  3042. $prodids = array();
  3043. $sql = "SELECT rowid";
  3044. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  3045. $sql .= " WHERE entity IN (".getEntity('product').")";
  3046. $sql .= $this->db->plimit(100);
  3047. $resql = $this->db->query($sql);
  3048. if ($resql) {
  3049. $num_prods = $this->db->num_rows($resql);
  3050. $i = 0;
  3051. while ($i < $num_prods) {
  3052. $i++;
  3053. $row = $this->db->fetch_row($resql);
  3054. $prodids[$i] = $row[0];
  3055. }
  3056. }
  3057. // Initialise parametres
  3058. $this->id = 0;
  3059. $this->ref = 'SPECIMEN';
  3060. $this->ref_client = 'NEMICEPS';
  3061. $this->specimen = 1;
  3062. $this->socid = 1;
  3063. $this->date = time();
  3064. $this->fin_validite = $this->date + 3600 * 24 * 30;
  3065. $this->cond_reglement_id = 1;
  3066. $this->cond_reglement_code = 'RECEP';
  3067. $this->mode_reglement_id = 7;
  3068. $this->mode_reglement_code = 'CHQ';
  3069. $this->availability_id = 1;
  3070. $this->availability_code = 'AV_NOW';
  3071. $this->demand_reason_id = 1;
  3072. $this->demand_reason_code = 'SRC_00';
  3073. $this->note_public = 'This is a comment (public)';
  3074. $this->note_private = 'This is a comment (private)';
  3075. $this->multicurrency_tx = 1;
  3076. $this->multicurrency_code = $conf->currency;
  3077. // Lines
  3078. $nbp = 5;
  3079. $xnbp = 0;
  3080. while ($xnbp < $nbp) {
  3081. $line = new PropaleLigne($this->db);
  3082. $line->desc = $langs->trans("Description")." ".$xnbp;
  3083. $line->qty = 1;
  3084. $line->subprice = 100;
  3085. $line->price = 100;
  3086. $line->tva_tx = 20;
  3087. $line->localtax1_tx = 0;
  3088. $line->localtax2_tx = 0;
  3089. if ($xnbp == 2) {
  3090. $line->total_ht = 50;
  3091. $line->total_ttc = 60;
  3092. $line->total_tva = 10;
  3093. $line->remise_percent = 50;
  3094. } else {
  3095. $line->total_ht = 100;
  3096. $line->total_ttc = 120;
  3097. $line->total_tva = 20;
  3098. $line->remise_percent = 00;
  3099. }
  3100. if ($num_prods > 0) {
  3101. $prodid = mt_rand(1, $num_prods);
  3102. $line->fk_product = $prodids[$prodid];
  3103. $line->product_ref = 'SPECIMEN';
  3104. }
  3105. $this->lines[$xnbp] = $line;
  3106. $this->total_ht += $line->total_ht;
  3107. $this->total_tva += $line->total_tva;
  3108. $this->total_ttc += $line->total_ttc;
  3109. $xnbp++;
  3110. }
  3111. }
  3112. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3113. /**
  3114. * Charge indicateurs this->nb de tableau de bord
  3115. *
  3116. * @return int <0 if ko, >0 if ok
  3117. */
  3118. public function load_state_board()
  3119. {
  3120. // phpcs:enable
  3121. global $user;
  3122. $this->nb = array();
  3123. $clause = "WHERE";
  3124. $sql = "SELECT count(p.rowid) as nb";
  3125. $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
  3126. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
  3127. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  3128. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  3129. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  3130. $clause = "AND";
  3131. }
  3132. $sql .= " ".$clause." p.entity IN (".getEntity('propal').")";
  3133. $resql = $this->db->query($sql);
  3134. if ($resql) {
  3135. // This assignment in condition is not a bug. It allows walking the results.
  3136. while ($obj = $this->db->fetch_object($resql)) {
  3137. $this->nb["proposals"] = $obj->nb;
  3138. }
  3139. $this->db->free($resql);
  3140. return 1;
  3141. } else {
  3142. dol_print_error($this->db);
  3143. $this->error = $this->db->error();
  3144. return -1;
  3145. }
  3146. }
  3147. /**
  3148. * Returns the reference to the following non used Proposal used depending on the active numbering module
  3149. * defined into PROPALE_ADDON
  3150. *
  3151. * @param Societe $soc Object thirdparty
  3152. * @return string Reference libre pour la propale
  3153. */
  3154. public function getNextNumRef($soc)
  3155. {
  3156. global $conf, $langs;
  3157. $langs->load("propal");
  3158. $classname = $conf->global->PROPALE_ADDON;
  3159. if (!empty($classname)) {
  3160. $mybool = false;
  3161. $file = $classname.".php";
  3162. // Include file with class
  3163. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  3164. foreach ($dirmodels as $reldir) {
  3165. $dir = dol_buildpath($reldir."core/modules/propale/");
  3166. // Load file with numbering class (if found)
  3167. $mybool |= @include_once $dir.$file;
  3168. }
  3169. if (!$mybool) {
  3170. dol_print_error('', "Failed to include file ".$file);
  3171. return '';
  3172. }
  3173. $obj = new $classname();
  3174. $numref = "";
  3175. $numref = $obj->getNextValue($soc, $this);
  3176. if ($numref != "") {
  3177. return $numref;
  3178. } else {
  3179. $this->error = $obj->error;
  3180. //dol_print_error($db,"Propale::getNextNumRef ".$obj->error);
  3181. return "";
  3182. }
  3183. } else {
  3184. $langs->load("errors");
  3185. print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Proposal"));
  3186. return "";
  3187. }
  3188. }
  3189. /**
  3190. * Return clicable link of object (with eventually picto)
  3191. *
  3192. * @param int $withpicto Add picto into link
  3193. * @param string $option Where point the link ('expedition', 'document', ...)
  3194. * @param string $get_params Parametres added to url
  3195. * @param int $notooltip 1=Disable tooltip
  3196. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  3197. * @param int $addlinktonotes -1=Disable, 0=Just add label show notes, 1=Add private note (only internal user), 2=Add public note (internal or external user), 3=Add private (internal user) and public note (internal and external user)
  3198. * @return string String with URL
  3199. */
  3200. public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = -1)
  3201. {
  3202. global $langs, $conf, $user, $hookmanager;
  3203. if (!empty($conf->dol_no_mouse_hover)) {
  3204. $notooltip = 1; // Force disable tooltips
  3205. }
  3206. $result = '';
  3207. $label = '';
  3208. $url = '';
  3209. if ($user->rights->propal->lire) {
  3210. $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Proposal").'</u>';
  3211. if (isset($this->statut)) {
  3212. $label .= ' '.$this->getLibStatut(5);
  3213. }
  3214. if (!empty($this->ref)) {
  3215. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  3216. }
  3217. if (!empty($this->ref_client)) {
  3218. $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
  3219. }
  3220. if (!empty($this->total_ht)) {
  3221. $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  3222. }
  3223. if (!empty($this->total_tva)) {
  3224. $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  3225. }
  3226. if (!empty($this->total_ttc)) {
  3227. $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  3228. }
  3229. if (!empty($this->date)) {
  3230. $label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
  3231. }
  3232. if (!empty($this->delivery_date)) {
  3233. $label .= '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
  3234. }
  3235. if ($option == '') {
  3236. $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id.$get_params;
  3237. } elseif ($option == 'compta') { // deprecated
  3238. $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id.$get_params;
  3239. } elseif ($option == 'expedition') {
  3240. $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id.$get_params;
  3241. } elseif ($option == 'document') {
  3242. $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id.$get_params;
  3243. }
  3244. if ($option != 'nolink') {
  3245. // Add param to save lastsearch_values or not
  3246. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  3247. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  3248. $add_save_lastsearch_values = 1;
  3249. }
  3250. if ($add_save_lastsearch_values) {
  3251. $url .= '&save_lastsearch_values=1';
  3252. }
  3253. }
  3254. }
  3255. $linkclose = '';
  3256. if (empty($notooltip) && $user->rights->propal->lire) {
  3257. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3258. $label = $langs->trans("Proposal");
  3259. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  3260. }
  3261. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  3262. $linkclose .= ' class="classfortooltip"';
  3263. }
  3264. $linkstart = '<a href="'.$url.'"';
  3265. $linkstart .= $linkclose.'>';
  3266. $linkend = '</a>';
  3267. $result .= $linkstart;
  3268. if ($withpicto) {
  3269. $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  3270. }
  3271. if ($withpicto != 2) {
  3272. $result .= $this->ref;
  3273. }
  3274. $result .= $linkend;
  3275. if ($addlinktonotes >= 0) {
  3276. $txttoshow = '';
  3277. if ($addlinktonotes == 0) {
  3278. if (!empty($this->note_private) || !empty($this->note_public)) {
  3279. $txttoshow = $langs->trans('ViewPrivateNote');
  3280. }
  3281. } elseif ($addlinktonotes == 1) {
  3282. if (!empty($this->note_private)) {
  3283. $txttoshow .= ($user->socid > 0 ? '' : dol_string_nohtmltag($this->note_private, 1));
  3284. }
  3285. } elseif ($addlinktonotes == 2) {
  3286. if (!empty($this->note_public)) {
  3287. $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
  3288. }
  3289. } elseif ($addlinktonotes == 3) {
  3290. if ($user->socid > 0) {
  3291. if (!empty($this->note_public)) {
  3292. $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
  3293. }
  3294. } else {
  3295. if (!empty($this->note_public)) {
  3296. $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
  3297. }
  3298. if (!empty($this->note_private)) {
  3299. if (!empty($txttoshow)) {
  3300. $txttoshow .= '<br><br>';
  3301. }
  3302. $txttoshow .= dol_string_nohtmltag($this->note_private, 1);
  3303. }
  3304. }
  3305. }
  3306. if ($txttoshow) {
  3307. $result .= ' <span class="note inline-block">';
  3308. $result .= '<a href="'.DOL_URL_ROOT.'/comm/propal/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($txttoshow).'">';
  3309. $result .= img_picto('', 'note');
  3310. $result .= '</a>';
  3311. $result .= '</span>';
  3312. }
  3313. }
  3314. global $action;
  3315. $hookmanager->initHooks(array($this->element . 'dao'));
  3316. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  3317. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3318. if ($reshook > 0) {
  3319. $result = $hookmanager->resPrint;
  3320. } else {
  3321. $result .= $hookmanager->resPrint;
  3322. }
  3323. return $result;
  3324. }
  3325. /**
  3326. * Retrieve an array of proposal lines
  3327. * @param string $filters Filter on other fields
  3328. *
  3329. * @return int >0 if OK, <0 if KO
  3330. */
  3331. public function getLinesArray($filters = '')
  3332. {
  3333. return $this->fetch_lines(0, 0, $filters);
  3334. }
  3335. /**
  3336. * Create a document onto disk according to template module.
  3337. *
  3338. * @param string $modele Force model to use ('' to not force)
  3339. * @param Translate $outputlangs Object langs to use for output
  3340. * @param int $hidedetails Hide details of lines
  3341. * @param int $hidedesc Hide description
  3342. * @param int $hideref Hide ref
  3343. * @param null|array $moreparams Array to provide more information
  3344. * @return int 0 if KO, 1 if OK
  3345. */
  3346. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  3347. {
  3348. global $conf, $langs;
  3349. $langs->load("propale");
  3350. $outputlangs->load("products");
  3351. if (!dol_strlen($modele)) {
  3352. $modele = 'azur';
  3353. if ($this->model_pdf) {
  3354. $modele = $this->model_pdf;
  3355. } elseif (!empty($conf->global->PROPALE_ADDON_PDF)) {
  3356. $modele = $conf->global->PROPALE_ADDON_PDF;
  3357. }
  3358. }
  3359. $modelpath = "core/modules/propale/doc/";
  3360. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  3361. }
  3362. /**
  3363. * Function used to replace a thirdparty id with another one.
  3364. *
  3365. * @param DoliDB $db Database handler
  3366. * @param int $origin_id Old thirdparty id
  3367. * @param int $dest_id New thirdparty id
  3368. * @return bool
  3369. */
  3370. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  3371. {
  3372. $tables = array(
  3373. 'propal'
  3374. );
  3375. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  3376. }
  3377. /**
  3378. * Function used to replace a product id with another one.
  3379. *
  3380. * @param DoliDB $db Database handler
  3381. * @param int $origin_id Old product id
  3382. * @param int $dest_id New product id
  3383. * @return bool
  3384. */
  3385. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  3386. {
  3387. $tables = array(
  3388. 'propaldet'
  3389. );
  3390. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  3391. }
  3392. }
  3393. /**
  3394. * Class to manage commercial proposal lines
  3395. */
  3396. class PropaleLigne extends CommonObjectLine
  3397. {
  3398. /**
  3399. * @var string ID to identify managed object
  3400. */
  3401. public $element = 'propaldet';
  3402. /**
  3403. * @var string Name of table without prefix where object is stored
  3404. */
  3405. public $table_element = 'propaldet';
  3406. public $oldline;
  3407. // From llx_propaldet
  3408. public $fk_propal;
  3409. public $fk_parent_line;
  3410. public $desc; // Description ligne
  3411. public $fk_product; // Id produit predefini
  3412. /**
  3413. * @deprecated
  3414. * @see $product_type
  3415. */
  3416. public $fk_product_type;
  3417. /**
  3418. * Product type.
  3419. * @var int
  3420. * @see Product::TYPE_PRODUCT, Product::TYPE_SERVICE
  3421. */
  3422. public $product_type = Product::TYPE_PRODUCT;
  3423. public $qty;
  3424. public $tva_tx;
  3425. public $vat_src_code;
  3426. public $subprice;
  3427. public $remise_percent;
  3428. public $fk_remise_except;
  3429. public $rang = 0;
  3430. public $fk_fournprice;
  3431. public $pa_ht;
  3432. public $marge_tx;
  3433. public $marque_tx;
  3434. public $special_code; // Tag for special lines (exlusive tags)
  3435. // 1: frais de port
  3436. // 2: ecotaxe
  3437. // 3: option line (when qty = 0)
  3438. public $info_bits = 0; // Some other info:
  3439. // Bit 0: 0 si TVA normal - 1 si TVA NPR
  3440. // Bit 1: 0 ligne normale - 1 si ligne de remise fixe
  3441. public $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne
  3442. public $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne
  3443. public $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne
  3444. /**
  3445. * @deprecated
  3446. * @see $remise_percent, $fk_remise_except
  3447. */
  3448. public $remise;
  3449. /**
  3450. * @deprecated
  3451. * @see $subprice
  3452. */
  3453. public $price;
  3454. // From llx_product
  3455. /**
  3456. * @deprecated
  3457. * @see $product_ref
  3458. */
  3459. public $ref;
  3460. /**
  3461. * Product reference
  3462. * @var string
  3463. */
  3464. public $product_ref;
  3465. /**
  3466. * @deprecated
  3467. * @see $product_label
  3468. */
  3469. public $libelle;
  3470. /**
  3471. * @deprecated
  3472. * @see $product_label
  3473. */
  3474. public $label;
  3475. /**
  3476. * Product label
  3477. * @var string
  3478. */
  3479. public $product_label;
  3480. /**
  3481. * Product description
  3482. * @var string
  3483. */
  3484. public $product_desc;
  3485. /**
  3486. * Product use lot
  3487. * @var string
  3488. */
  3489. public $product_tobatch;
  3490. /**
  3491. * Product barcode
  3492. * @var string
  3493. */
  3494. public $product_barcode;
  3495. public $localtax1_tx; // Local tax 1
  3496. public $localtax2_tx; // Local tax 2
  3497. public $localtax1_type; // Local tax 1 type
  3498. public $localtax2_type; // Local tax 2 type
  3499. public $total_localtax1; // Line total local tax 1
  3500. public $total_localtax2; // Line total local tax 2
  3501. public $date_start;
  3502. public $date_end;
  3503. public $skip_update_total; // Skip update price total for special lines
  3504. // Multicurrency
  3505. public $fk_multicurrency;
  3506. public $multicurrency_code;
  3507. public $multicurrency_subprice;
  3508. public $multicurrency_total_ht;
  3509. public $multicurrency_total_tva;
  3510. public $multicurrency_total_ttc;
  3511. /**
  3512. * Class line Contructor
  3513. *
  3514. * @param DoliDB $db Database handler
  3515. */
  3516. public function __construct($db)
  3517. {
  3518. $this->db = $db;
  3519. }
  3520. /**
  3521. * Retrieve the propal line object
  3522. *
  3523. * @param int $rowid Propal line id
  3524. * @return int <0 if KO, >0 if OK
  3525. */
  3526. public function fetch($rowid)
  3527. {
  3528. $sql = 'SELECT pd.rowid, pd.fk_propal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.vat_src_code, pd.tva_tx,';
  3529. $sql .= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,';
  3530. $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,';
  3531. $sql .= ' pd.fk_unit,';
  3532. $sql .= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,';
  3533. $sql .= ' pd.fk_multicurrency, pd.multicurrency_code, pd.multicurrency_subprice, pd.multicurrency_total_ht, pd.multicurrency_total_tva, pd.multicurrency_total_ttc,';
  3534. $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,';
  3535. $sql .= ' pd.date_start, pd.date_end, pd.product_type';
  3536. $sql .= ' FROM '.MAIN_DB_PREFIX.'propaldet as pd';
  3537. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid';
  3538. $sql .= ' WHERE pd.rowid = '.((int) $rowid);
  3539. $result = $this->db->query($sql);
  3540. if ($result) {
  3541. $objp = $this->db->fetch_object($result);
  3542. if ($objp) {
  3543. $this->id = $objp->rowid;
  3544. $this->rowid = $objp->rowid; // deprecated
  3545. $this->fk_propal = $objp->fk_propal;
  3546. $this->fk_parent_line = $objp->fk_parent_line;
  3547. $this->label = $objp->custom_label;
  3548. $this->desc = $objp->description;
  3549. $this->qty = $objp->qty;
  3550. $this->price = $objp->price; // deprecated
  3551. $this->subprice = $objp->subprice;
  3552. $this->vat_src_code = $objp->vat_src_code;
  3553. $this->tva_tx = $objp->tva_tx;
  3554. $this->remise = $objp->remise; // deprecated
  3555. $this->remise_percent = $objp->remise_percent;
  3556. $this->fk_remise_except = $objp->fk_remise_except;
  3557. $this->fk_product = $objp->fk_product;
  3558. $this->info_bits = $objp->info_bits;
  3559. $this->total_ht = $objp->total_ht;
  3560. $this->total_tva = $objp->total_tva;
  3561. $this->total_ttc = $objp->total_ttc;
  3562. $this->fk_fournprice = $objp->fk_fournprice;
  3563. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
  3564. $this->pa_ht = $marginInfos[0];
  3565. $this->marge_tx = $marginInfos[1];
  3566. $this->marque_tx = $marginInfos[2];
  3567. $this->special_code = $objp->special_code;
  3568. $this->product_type = $objp->product_type;
  3569. $this->rang = $objp->rang;
  3570. $this->ref = $objp->product_ref; // deprecated
  3571. $this->product_ref = $objp->product_ref;
  3572. $this->libelle = $objp->product_label; // deprecated
  3573. $this->product_label = $objp->product_label;
  3574. $this->product_desc = $objp->product_desc;
  3575. $this->fk_unit = $objp->fk_unit;
  3576. $this->date_start = $this->db->jdate($objp->date_start);
  3577. $this->date_end = $this->db->jdate($objp->date_end);
  3578. // Multicurrency
  3579. $this->fk_multicurrency = $objp->fk_multicurrency;
  3580. $this->multicurrency_code = $objp->multicurrency_code;
  3581. $this->multicurrency_subprice = $objp->multicurrency_subprice;
  3582. $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
  3583. $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
  3584. $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  3585. $this->fetch_optionals();
  3586. $this->db->free($result);
  3587. return 1;
  3588. } else {
  3589. return 0;
  3590. }
  3591. } else {
  3592. return -1;
  3593. }
  3594. }
  3595. /**
  3596. * Insert object line propal in database
  3597. *
  3598. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3599. * @return int <0 if KO, >0 if OK
  3600. */
  3601. public function insert($notrigger = 0)
  3602. {
  3603. global $conf, $user;
  3604. $error = 0;
  3605. dol_syslog(get_class($this)."::insert rang=".$this->rang);
  3606. $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
  3607. // Clean parameters
  3608. if (empty($this->tva_tx)) {
  3609. $this->tva_tx = 0;
  3610. }
  3611. if (empty($this->localtax1_tx)) {
  3612. $this->localtax1_tx = 0;
  3613. }
  3614. if (empty($this->localtax2_tx)) {
  3615. $this->localtax2_tx = 0;
  3616. }
  3617. if (empty($this->localtax1_type)) {
  3618. $this->localtax1_type = 0;
  3619. }
  3620. if (empty($this->localtax2_type)) {
  3621. $this->localtax2_type = 0;
  3622. }
  3623. if (empty($this->total_localtax1)) {
  3624. $this->total_localtax1 = 0;
  3625. }
  3626. if (empty($this->total_localtax2)) {
  3627. $this->total_localtax2 = 0;
  3628. }
  3629. if (empty($this->rang)) {
  3630. $this->rang = 0;
  3631. }
  3632. if (empty($this->remise_percent) || !is_numeric($this->remise_percent)) {
  3633. $this->remise_percent = 0;
  3634. }
  3635. if (empty($this->info_bits)) {
  3636. $this->info_bits = 0;
  3637. }
  3638. if (empty($this->special_code)) {
  3639. $this->special_code = 0;
  3640. }
  3641. if (empty($this->fk_parent_line)) {
  3642. $this->fk_parent_line = 0;
  3643. }
  3644. if (empty($this->fk_fournprice)) {
  3645. $this->fk_fournprice = 0;
  3646. }
  3647. if (!is_numeric($this->qty)) {
  3648. $this->qty = 0;
  3649. }
  3650. if (empty($this->pa_ht)) {
  3651. $this->pa_ht = 0;
  3652. }
  3653. if (empty($this->multicurrency_subprice)) {
  3654. $this->multicurrency_subprice = 0;
  3655. }
  3656. if (empty($this->multicurrency_total_ht)) {
  3657. $this->multicurrency_total_ht = 0;
  3658. }
  3659. if (empty($this->multicurrency_total_tva)) {
  3660. $this->multicurrency_total_tva = 0;
  3661. }
  3662. if (empty($this->multicurrency_total_ttc)) {
  3663. $this->multicurrency_total_ttc = 0;
  3664. }
  3665. // if buy price not defined, define buyprice as configured in margin admin
  3666. if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
  3667. if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
  3668. return $result;
  3669. } else {
  3670. $this->pa_ht = $result;
  3671. }
  3672. }
  3673. // Check parameters
  3674. if ($this->product_type < 0) {
  3675. return -1;
  3676. }
  3677. $this->db->begin();
  3678. // Insert line into database
  3679. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet';
  3680. $sql .= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,';
  3681. $sql .= ' fk_remise_except, qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
  3682. $sql .= ' subprice, remise_percent, ';
  3683. $sql .= ' info_bits, ';
  3684. $sql .= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,';
  3685. $sql .= ' fk_unit,';
  3686. $sql .= ' date_start, date_end';
  3687. $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc)';
  3688. $sql .= " VALUES (".$this->fk_propal.",";
  3689. $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").",";
  3690. $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
  3691. $sql .= " '".$this->db->escape($this->desc)."',";
  3692. $sql .= " ".($this->fk_product ? "'".$this->db->escape($this->fk_product)."'" : "null").",";
  3693. $sql .= " '".$this->db->escape($this->product_type)."',";
  3694. $sql .= " ".($this->fk_remise_except ? "'".$this->db->escape($this->fk_remise_except)."'" : "null").",";
  3695. $sql .= " ".price2num($this->qty, 'MS').",";
  3696. $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
  3697. $sql .= " ".price2num($this->tva_tx).",";
  3698. $sql .= " ".price2num($this->localtax1_tx).",";
  3699. $sql .= " ".price2num($this->localtax2_tx).",";
  3700. $sql .= " '".$this->db->escape($this->localtax1_type)."',";
  3701. $sql .= " '".$this->db->escape($this->localtax2_type)."',";
  3702. $sql .= " ".(price2num($this->subprice) !== '' ? price2num($this->subprice, 'MU') : "null").",";
  3703. $sql .= " ".price2num($this->remise_percent, 3).",";
  3704. $sql .= " ".(isset($this->info_bits) ? ((int) $this->info_bits) : "null").",";
  3705. $sql .= " ".price2num($this->total_ht, 'MT').",";
  3706. $sql .= " ".price2num($this->total_tva, 'MT').",";
  3707. $sql .= " ".price2num($this->total_localtax1, 'MT').",";
  3708. $sql .= " ".price2num($this->total_localtax2, 'MT').",";
  3709. $sql .= " ".price2num($this->total_ttc, 'MT').",";
  3710. $sql .= " ".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null").",";
  3711. $sql .= " ".(isset($this->pa_ht) ? "'".price2num($this->pa_ht)."'" : "null").",";
  3712. $sql .= ' '.((int) $this->special_code).',';
  3713. $sql .= ' '.((int) $this->rang).',';
  3714. $sql .= ' '.(empty($this->fk_unit) ? 'NULL' : ((int) $this->fk_unit)).',';
  3715. $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").',';
  3716. $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
  3717. $sql .= ", ".($this->fk_multicurrency > 0 ? ((int) $this->fk_multicurrency) : 'null');
  3718. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  3719. $sql .= ", ".price2num($this->multicurrency_subprice, 'CU');
  3720. $sql .= ", ".price2num($this->multicurrency_total_ht, 'CT');
  3721. $sql .= ", ".price2num($this->multicurrency_total_tva, 'CT');
  3722. $sql .= ", ".price2num($this->multicurrency_total_ttc, 'CT');
  3723. $sql .= ')';
  3724. dol_syslog(get_class($this).'::insert', LOG_DEBUG);
  3725. $resql = $this->db->query($sql);
  3726. if ($resql) {
  3727. $this->rowid = $this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet');
  3728. if (!$error) {
  3729. $this->id = $this->rowid;
  3730. $result = $this->insertExtraFields();
  3731. if ($result < 0) {
  3732. $error++;
  3733. }
  3734. }
  3735. if (!$error && !$notrigger) {
  3736. // Call trigger
  3737. $result = $this->call_trigger('LINEPROPAL_INSERT', $user);
  3738. if ($result < 0) {
  3739. $this->db->rollback();
  3740. return -1;
  3741. }
  3742. // End call triggers
  3743. }
  3744. $this->db->commit();
  3745. return 1;
  3746. } else {
  3747. $this->error = $this->db->error()." sql=".$sql;
  3748. $this->db->rollback();
  3749. return -1;
  3750. }
  3751. }
  3752. /**
  3753. * Delete line in database
  3754. *
  3755. * @param User $user Object user
  3756. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3757. * @return int <0 if ko, >0 if ok
  3758. */
  3759. public function delete(User $user, $notrigger = 0)
  3760. {
  3761. global $conf;
  3762. $error = 0;
  3763. $this->db->begin();
  3764. if (!$notrigger) {
  3765. // Call trigger
  3766. $result = $this->call_trigger('LINEPROPAL_DELETE', $user);
  3767. if ($result < 0) {
  3768. $error++;
  3769. }
  3770. }
  3771. // End call triggers
  3772. if (!$error) {
  3773. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "propaldet WHERE rowid = " . ((int) $this->rowid);
  3774. dol_syslog("PropaleLigne::delete", LOG_DEBUG);
  3775. if ($this->db->query($sql)) {
  3776. // Remove extrafields
  3777. if (!$error) {
  3778. $this->id = $this->rowid;
  3779. $result = $this->deleteExtraFields();
  3780. if ($result < 0) {
  3781. $error++;
  3782. dol_syslog(get_class($this) . "::delete error -4 " . $this->error, LOG_ERR);
  3783. }
  3784. }
  3785. } else {
  3786. $this->error = $this->db->error() . " sql=" . $sql;
  3787. $error++;
  3788. }
  3789. }
  3790. if ($error) {
  3791. $this->db->rollback();
  3792. return -1;
  3793. } else {
  3794. $this->db->commit();
  3795. return 1;
  3796. }
  3797. }
  3798. /**
  3799. * Update propal line object into DB
  3800. *
  3801. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3802. * @return int <0 if ko, >0 if ok
  3803. */
  3804. public function update($notrigger = 0)
  3805. {
  3806. global $conf, $user;
  3807. $error = 0;
  3808. $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
  3809. if (empty($this->id) && !empty($this->rowid)) {
  3810. $this->id = $this->rowid;
  3811. }
  3812. // Clean parameters
  3813. if (empty($this->tva_tx)) {
  3814. $this->tva_tx = 0;
  3815. }
  3816. if (empty($this->localtax1_tx)) {
  3817. $this->localtax1_tx = 0;
  3818. }
  3819. if (empty($this->localtax2_tx)) {
  3820. $this->localtax2_tx = 0;
  3821. }
  3822. if (empty($this->total_localtax1)) {
  3823. $this->total_localtax1 = 0;
  3824. }
  3825. if (empty($this->total_localtax2)) {
  3826. $this->total_localtax2 = 0;
  3827. }
  3828. if (empty($this->localtax1_type)) {
  3829. $this->localtax1_type = 0;
  3830. }
  3831. if (empty($this->localtax2_type)) {
  3832. $this->localtax2_type = 0;
  3833. }
  3834. if (empty($this->marque_tx)) {
  3835. $this->marque_tx = 0;
  3836. }
  3837. if (empty($this->marge_tx)) {
  3838. $this->marge_tx = 0;
  3839. }
  3840. if (empty($this->price)) {
  3841. $this->price = 0; // TODO A virer
  3842. }
  3843. if (empty($this->remise_percent)) {
  3844. $this->remise_percent = 0;
  3845. }
  3846. if (empty($this->info_bits)) {
  3847. $this->info_bits = 0;
  3848. }
  3849. if (empty($this->special_code)) {
  3850. $this->special_code = 0;
  3851. }
  3852. if (empty($this->fk_parent_line)) {
  3853. $this->fk_parent_line = 0;
  3854. }
  3855. if (empty($this->fk_fournprice)) {
  3856. $this->fk_fournprice = 0;
  3857. }
  3858. if (empty($this->subprice)) {
  3859. $this->subprice = 0;
  3860. }
  3861. if (empty($this->pa_ht)) {
  3862. $this->pa_ht = 0;
  3863. }
  3864. // if buy price not defined, define buyprice as configured in margin admin
  3865. if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
  3866. if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
  3867. return $result;
  3868. } else {
  3869. $this->pa_ht = $result;
  3870. }
  3871. }
  3872. $this->db->begin();
  3873. // Mise a jour ligne en base
  3874. $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET";
  3875. $sql .= " description='".$this->db->escape($this->desc)."'";
  3876. $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
  3877. $sql .= ", product_type=".$this->product_type;
  3878. $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'";
  3879. $sql .= ", tva_tx='".price2num($this->tva_tx)."'";
  3880. $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
  3881. $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
  3882. $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
  3883. $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
  3884. $sql .= ", qty='".price2num($this->qty)."'";
  3885. $sql .= ", subprice=".price2num($this->subprice)."";
  3886. $sql .= ", remise_percent=".price2num($this->remise_percent)."";
  3887. $sql .= ", price=".(float) price2num($this->price).""; // TODO A virer
  3888. $sql .= ", remise=".(float) price2num($this->remise).""; // TODO A virer
  3889. $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
  3890. if (empty($this->skip_update_total)) {
  3891. $sql .= ", total_ht=".price2num($this->total_ht)."";
  3892. $sql .= ", total_tva=".price2num($this->total_tva)."";
  3893. $sql .= ", total_ttc=".price2num($this->total_ttc)."";
  3894. $sql .= ", total_localtax1=".price2num($this->total_localtax1)."";
  3895. $sql .= ", total_localtax2=".price2num($this->total_localtax2)."";
  3896. }
  3897. $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
  3898. $sql .= ", buy_price_ht=".price2num($this->pa_ht);
  3899. if (strlen($this->special_code)) {
  3900. $sql .= ", special_code=".$this->special_code;
  3901. }
  3902. $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
  3903. if (!empty($this->rang)) {
  3904. $sql .= ", rang=".((int) $this->rang);
  3905. }
  3906. $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
  3907. $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
  3908. $sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
  3909. // Multicurrency
  3910. $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
  3911. $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
  3912. $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
  3913. $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
  3914. $sql .= " WHERE rowid = ".((int) $this->id);
  3915. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  3916. $resql = $this->db->query($sql);
  3917. if ($resql) {
  3918. if (!$error) {
  3919. $result = $this->insertExtraFields();
  3920. if ($result < 0) {
  3921. $error++;
  3922. }
  3923. }
  3924. if (!$error && !$notrigger) {
  3925. // Call trigger
  3926. $result = $this->call_trigger('LINEPROPAL_MODIFY', $user);
  3927. if ($result < 0) {
  3928. $this->db->rollback();
  3929. return -1;
  3930. }
  3931. // End call triggers
  3932. }
  3933. $this->db->commit();
  3934. return 1;
  3935. } else {
  3936. $this->error = $this->db->error();
  3937. $this->db->rollback();
  3938. return -2;
  3939. }
  3940. }
  3941. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3942. /**
  3943. * Update DB line fields total_xxx
  3944. * Used by migration
  3945. *
  3946. * @return int <0 if KO, >0 if OK
  3947. */
  3948. public function update_total()
  3949. {
  3950. // phpcs:enable
  3951. $this->db->begin();
  3952. // Mise a jour ligne en base
  3953. $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET";
  3954. $sql .= " total_ht=".price2num($this->total_ht, 'MT')."";
  3955. $sql .= ",total_tva=".price2num($this->total_tva, 'MT')."";
  3956. $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT')."";
  3957. $sql .= " WHERE rowid = ".((int) $this->rowid);
  3958. dol_syslog("PropaleLigne::update_total", LOG_DEBUG);
  3959. $resql = $this->db->query($sql);
  3960. if ($resql) {
  3961. $this->db->commit();
  3962. return 1;
  3963. } else {
  3964. $this->error = $this->db->error();
  3965. $this->db->rollback();
  3966. return -2;
  3967. }
  3968. }
  3969. }