propal.class.php 146 KB

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