propal.class.php 146 KB

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