commande.class.php 156 KB

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