commande.class.php 159 KB

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