propal.class.php 152 KB

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