propal.class.php 147 KB

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