propal.class.php 152 KB

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