expensereport.class.php 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091
  1. <?php
  2. /* Copyright (C) 2011 Dimitri Mouillard <dmouillard@teclib.com>
  3. * Copyright (C) 2015 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
  5. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  6. * Copyright (c) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  7. * Copyright (C) 2016-2020 Ferran Marcet <fmarcet@2byte.es>
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  21. */
  22. /**
  23. * \file htdocs/expensereport/class/expensereport.class.php
  24. * \ingroup expensereport
  25. * \brief File to manage Expense Reports
  26. */
  27. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  28. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  29. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php';
  30. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.php';
  31. /**
  32. * Class to manage Trips and Expenses
  33. */
  34. class ExpenseReport extends CommonObject
  35. {
  36. /**
  37. * @var string ID to identify managed object
  38. */
  39. public $element = 'expensereport';
  40. /**
  41. * @var string Name of table without prefix where object is stored
  42. */
  43. public $table_element = 'expensereport';
  44. /**
  45. * @var string table element line name
  46. */
  47. public $table_element_line = 'expensereport_det';
  48. /**
  49. * @var string Fieldname with ID of parent key if this field has a parent
  50. */
  51. public $fk_element = 'fk_expensereport';
  52. /**
  53. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  54. */
  55. public $picto = 'trip';
  56. public $lines = array();
  57. public $date_debut;
  58. public $date_fin;
  59. /**
  60. * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=paid, 99=denied
  61. *
  62. * @var int Status
  63. */
  64. public $status;
  65. /**
  66. * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=paid, 99=denied
  67. *
  68. * @var int Status
  69. * @deprecated
  70. */
  71. public $fk_statut;
  72. public $fk_c_paiement;
  73. public $paid;
  74. public $user_author_infos;
  75. public $user_validator_infos;
  76. public $rule_warning_message;
  77. // ACTIONS
  78. // Create
  79. public $date_create;
  80. public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
  81. // Update
  82. public $date_modif;
  83. public $fk_user_modif;
  84. // Refus
  85. public $date_refuse;
  86. public $detail_refuse;
  87. public $fk_user_refuse;
  88. // Annulation
  89. public $date_cancel;
  90. public $detail_cancel;
  91. public $fk_user_cancel;
  92. public $fk_user_validator; // User that is defined to approve
  93. // Validation
  94. /* @deprecated */
  95. public $datevalid;
  96. public $date_valid; // User making validation
  97. public $fk_user_valid;
  98. public $user_valid_infos;
  99. // Approve
  100. public $date_approve;
  101. public $fk_user_approve; // User that has approved
  102. // Paiement
  103. public $user_paid_infos;
  104. public $localtax1; // for backward compatibility (real field should be total_localtax1 defined into CommonObject)
  105. public $localtax2; // for backward compatibility (real field should be total_localtax2 defined into CommonObject)
  106. public $statuts = array();
  107. public $statuts_short = array();
  108. public $statuts_logo;
  109. // Multicurrency
  110. /**
  111. * @var int Currency ID
  112. */
  113. public $fk_multicurrency;
  114. /**
  115. * @var string multicurrency code
  116. */
  117. public $multicurrency_code;
  118. public $multicurrency_tx;
  119. public $multicurrency_total_ht;
  120. public $multicurrency_total_tva;
  121. public $multicurrency_total_ttc;
  122. /**
  123. * Draft status
  124. */
  125. const STATUS_DRAFT = 0;
  126. /**
  127. * Validated (need to be paid)
  128. */
  129. const STATUS_VALIDATED = 2;
  130. /**
  131. * Classified canceled
  132. */
  133. const STATUS_CANCELED = 4;
  134. /**
  135. * Classified approved
  136. */
  137. const STATUS_APPROVED = 5;
  138. /**
  139. * Classified refused
  140. */
  141. const STATUS_REFUSED = 99;
  142. /**
  143. * Classified paid.
  144. */
  145. const STATUS_CLOSED = 6;
  146. public $fields = array(
  147. 'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  148. 'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>15),
  149. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20),
  150. 'ref_number_int' =>array('type'=>'integer', 'label'=>'Ref number int', 'enabled'=>1, 'visible'=>-1, 'position'=>25),
  151. 'ref_ext' =>array('type'=>'integer', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
  152. 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'Total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>35),
  153. 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'Total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
  154. 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
  155. 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
  156. 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
  157. 'date_debut' =>array('type'=>'date', 'label'=>'Date debut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>60),
  158. 'date_fin' =>array('type'=>'date', 'label'=>'Date fin', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>65),
  159. 'date_valid' =>array('type'=>'datetime', 'label'=>'Date valid', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
  160. 'date_approve' =>array('type'=>'datetime', 'label'=>'Date approve', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
  161. 'date_refuse' =>array('type'=>'datetime', 'label'=>'Date refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
  162. 'date_cancel' =>array('type'=>'datetime', 'label'=>'Date cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  163. 'fk_user_author' =>array('type'=>'integer', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>100),
  164. 'fk_user_modif' =>array('type'=>'integer', 'label'=>'Fk user modif', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
  165. 'fk_user_valid' =>array('type'=>'integer', 'label'=>'Fk user valid', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
  166. 'fk_user_validator' =>array('type'=>'integer', 'label'=>'Fk user validator', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
  167. 'fk_user_approve' =>array('type'=>'integer', 'label'=>'Fk user approve', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
  168. 'fk_user_refuse' =>array('type'=>'integer', 'label'=>'Fk user refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
  169. 'fk_user_cancel' =>array('type'=>'integer', 'label'=>'Fk user cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
  170. 'fk_c_paiement' =>array('type'=>'integer', 'label'=>'Fk c paiement', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
  171. 'paid' =>array('type'=>'integer', 'label'=>'Paid', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>145),
  172. 'note_public' =>array('type'=>'text', 'label'=>'Note public', 'enabled'=>1, 'visible'=>0, 'position'=>150),
  173. 'note_private' =>array('type'=>'text', 'label'=>'Note private', 'enabled'=>1, 'visible'=>0, 'position'=>155),
  174. 'detail_refuse' =>array('type'=>'varchar(255)', 'label'=>'Detail refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
  175. 'detail_cancel' =>array('type'=>'varchar(255)', 'label'=>'Detail cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
  176. 'integration_compta' =>array('type'=>'integer', 'label'=>'Integration compta', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
  177. 'fk_bank_account' =>array('type'=>'integer', 'label'=>'Fk bank account', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
  178. 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
  179. 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
  180. 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency tx', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
  181. 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
  182. 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
  183. 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
  184. 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>220),
  185. 'date_create' =>array('type'=>'datetime', 'label'=>'Date create', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>300),
  186. 'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>305),
  187. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>1000),
  188. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>1010),
  189. 'fk_statut' =>array('type'=>'integer', 'label'=>'Fk statut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
  190. );
  191. /**
  192. * Constructor
  193. *
  194. * @param DoliDB $db Handler acces base de donnees
  195. */
  196. public function __construct($db)
  197. {
  198. $this->db = $db;
  199. $this->total_ht = 0;
  200. $this->total_ttc = 0;
  201. $this->total_tva = 0;
  202. $this->total_localtax1 = 0;
  203. $this->total_localtax2 = 0;
  204. $this->localtax1 = 0; // For backward compatibility
  205. $this->localtax2 = 0; // For backward compatibility
  206. $this->modepaymentid = 0;
  207. // List of language codes for status
  208. $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
  209. $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
  210. $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5');
  211. }
  212. /**
  213. * Create object in database
  214. *
  215. * @param User $user User that create
  216. * @param int $notrigger Disable triggers
  217. * @return int <0 if KO, >0 if OK
  218. */
  219. public function create($user, $notrigger = 0)
  220. {
  221. global $conf, $langs;
  222. $now = dol_now();
  223. $error = 0;
  224. // Check parameters
  225. if (empty($this->date_debut) || empty($this->date_fin)) {
  226. $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date'));
  227. return -1;
  228. }
  229. $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
  230. if (empty($fuserid)) {
  231. $fuserid = $user->id;
  232. }
  233. $this->db->begin();
  234. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
  235. $sql .= "ref";
  236. $sql .= ",total_ht";
  237. $sql .= ",total_ttc";
  238. $sql .= ",total_tva";
  239. $sql .= ",date_debut";
  240. $sql .= ",date_fin";
  241. $sql .= ",date_create";
  242. $sql .= ",fk_user_creat";
  243. $sql .= ",fk_user_author";
  244. $sql .= ",fk_user_validator";
  245. $sql .= ",fk_user_approve";
  246. $sql .= ",fk_user_modif";
  247. $sql .= ",fk_statut";
  248. $sql .= ",fk_c_paiement";
  249. $sql .= ",paid";
  250. $sql .= ",note_public";
  251. $sql .= ",note_private";
  252. $sql .= ",entity";
  253. $sql .= ") VALUES(";
  254. $sql .= "'(PROV)'";
  255. $sql .= ", ".price2num($this->total_ht, 'MT');
  256. $sql .= ", ".price2num($this->total_ttc, 'MT');
  257. $sql .= ", ".price2num($this->total_tva, 'MT');
  258. $sql .= ", '".$this->db->idate($this->date_debut)."'";
  259. $sql .= ", '".$this->db->idate($this->date_fin)."'";
  260. $sql .= ", '".$this->db->idate($now)."'";
  261. $sql .= ", ".((int) $user->id);
  262. $sql .= ", ".((int) $fuserid);
  263. $sql .= ", ".($this->fk_user_validator > 0 ? ((int) $this->fk_user_validator) : "null");
  264. $sql .= ", ".($this->fk_user_approve > 0 ? ((int) $this->fk_user_approve) : "null");
  265. $sql .= ", ".($this->fk_user_modif > 0 ? ((int) $this->fk_user_modif) : "null");
  266. $sql .= ", ".($this->fk_statut > 1 ? ((int) $this->fk_statut) : 0);
  267. $sql .= ", ".($this->modepaymentid ? ((int) $this->modepaymentid) : "null");
  268. $sql .= ", 0";
  269. $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
  270. $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
  271. $sql .= ", ".((int) $conf->entity);
  272. $sql .= ")";
  273. $result = $this->db->query($sql);
  274. if ($result) {
  275. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  276. $this->ref = '(PROV'.$this->id.')';
  277. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
  278. $resql = $this->db->query($sql);
  279. if (!$resql) {
  280. $this->error = $this->db->lasterror();
  281. $error++;
  282. }
  283. if (!$error) {
  284. if (is_array($this->lines) && count($this->lines) > 0) {
  285. foreach ($this->lines as $line) {
  286. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  287. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  288. if (!is_object($line)) {
  289. $line = (object) $line;
  290. $newndfline = new ExpenseReportLine($this->db);
  291. $newndfline->fk_expensereport = $line->fk_expensereport;
  292. $newndfline->fk_c_type_fees = $line->fk_c_type_fees;
  293. $newndfline->fk_project = $line->fk_project;
  294. $newndfline->vatrate = $line->vatrate;
  295. $newndfline->vat_src_code = $line->vat_src_code;
  296. $newndfline->localtax1_tx = $line->localtax1_tx;
  297. $newndfline->localtax2_tx = $line->localtax2_tx;
  298. $newndfline->localtax1_type = $line->localtax1_type;
  299. $newndfline->localtax2_type = $line->localtax2_type;
  300. $newndfline->comments = $line->comments;
  301. $newndfline->qty = $line->qty;
  302. $newndfline->value_unit = $line->value_unit;
  303. $newndfline->total_ht = $line->total_ht;
  304. $newndfline->total_ttc = $line->total_ttc;
  305. $newndfline->total_tva = $line->total_tva;
  306. $newndfline->total_localtax1 = $line->total_localtax1;
  307. $newndfline->total_localtax2 = $line->total_localtax2;
  308. $newndfline->date = $line->date;
  309. $newndfline->rule_warning_message = $line->rule_warning_message;
  310. $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat;
  311. $newndfline->fk_ecm_files = $line->fk_ecm_files;
  312. } else {
  313. $newndfline = $line;
  314. }
  315. //$newndfline=new ExpenseReportLine($this->db);
  316. $newndfline->fk_expensereport = $this->id;
  317. $result = $newndfline->insert();
  318. if ($result < 0) {
  319. $this->error = $newndfline->error;
  320. $this->errors = $newndfline->errors;
  321. $error++;
  322. break;
  323. }
  324. }
  325. }
  326. }
  327. if (!$error) {
  328. $result = $this->insertExtraFields();
  329. if ($result < 0) {
  330. $error++;
  331. }
  332. }
  333. if (!$error) {
  334. $result = $this->update_price(1);
  335. if ($result > 0) {
  336. if (!$notrigger) {
  337. // Call trigger
  338. $result = $this->call_trigger('EXPENSE_REPORT_CREATE', $user);
  339. if ($result < 0) {
  340. $error++;
  341. }
  342. // End call triggers
  343. }
  344. if (empty($error)) {
  345. $this->db->commit();
  346. return $this->id;
  347. } else {
  348. $this->db->rollback();
  349. return -4;
  350. }
  351. } else {
  352. $this->db->rollback();
  353. return -3;
  354. }
  355. } else {
  356. dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
  357. $this->db->rollback();
  358. return -2;
  359. }
  360. } else {
  361. $this->error = $this->db->lasterror()." sql=".$sql;
  362. $this->db->rollback();
  363. return -1;
  364. }
  365. }
  366. /**
  367. * Load an object from its id and create a new one in database
  368. *
  369. * @param User $user User making the clone
  370. * @param int $fk_user_author Id of new user
  371. * @return int New id of clone
  372. */
  373. public function createFromClone(User $user, $fk_user_author)
  374. {
  375. global $hookmanager;
  376. $error = 0;
  377. if (empty($fk_user_author)) {
  378. $fk_user_author = $user->id;
  379. }
  380. $this->db->begin();
  381. // get extrafields so they will be clone
  382. //foreach($this->lines as $line)
  383. //$line->fetch_optionals();
  384. // Load source object
  385. $objFrom = clone $this;
  386. $this->id = 0;
  387. $this->ref = '';
  388. $this->status = 0;
  389. $this->fk_statut = 0; // deprecated
  390. // Clear fields
  391. $this->fk_user_creat = $user->id;
  392. $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
  393. $this->fk_user_valid = '';
  394. $this->date_create = '';
  395. $this->date_creation = '';
  396. $this->date_validation = '';
  397. // Remove link on lines to a joined file
  398. if (is_array($this->lines) && count($this->lines) > 0) {
  399. foreach ($this->lines as $key => $line) {
  400. $this->lines[$key]->fk_ecm_files = 0;
  401. }
  402. }
  403. // Create clone
  404. $this->context['createfromclone'] = 'createfromclone';
  405. $result = $this->create($user);
  406. if ($result < 0) {
  407. $error++;
  408. }
  409. if (!$error) {
  410. // Hook of thirdparty module
  411. if (is_object($hookmanager)) {
  412. $parameters = array('objFrom'=>$objFrom);
  413. $action = '';
  414. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  415. if ($reshook < 0) {
  416. $this->errors += $hookmanager->errors;
  417. $this->error = $hookmanager->error;
  418. $error++;
  419. }
  420. }
  421. }
  422. unset($this->context['createfromclone']);
  423. // End
  424. if (!$error) {
  425. $this->db->commit();
  426. return $this->id;
  427. } else {
  428. $this->db->rollback();
  429. return -1;
  430. }
  431. }
  432. /**
  433. * update
  434. *
  435. * @param User $user User making change
  436. * @param int $notrigger Disable triggers
  437. * @param User $userofexpensereport New user we want to have the expense report on.
  438. * @return int <0 if KO, >0 if OK
  439. */
  440. public function update($user, $notrigger = 0, $userofexpensereport = null)
  441. {
  442. global $langs;
  443. $error = 0;
  444. $this->db->begin();
  445. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
  446. $sql .= " total_ht = ".$this->total_ht;
  447. $sql .= " , total_ttc = ".$this->total_ttc;
  448. $sql .= " , total_tva = ".$this->total_tva;
  449. $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'";
  450. $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'";
  451. if ($userofexpensereport && is_object($userofexpensereport)) {
  452. $sql .= " , fk_user_author = ".($userofexpensereport->id > 0 ? $userofexpensereport->id : "null"); // Note fk_user_author is not the 'author' but the guy the expense report is for.
  453. }
  454. $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
  455. $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null");
  456. $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
  457. $sql .= " , fk_user_modif = ".$user->id;
  458. $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0');
  459. $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null");
  460. $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''");
  461. $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''");
  462. $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''");
  463. $sql .= " WHERE rowid = ".((int) $this->id);
  464. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  465. $result = $this->db->query($sql);
  466. if ($result) {
  467. if (!$notrigger) {
  468. // Call trigger
  469. $result = $this->call_trigger('EXPENSE_REPORT_MODIFY', $user);
  470. if ($result < 0) {
  471. $error++;
  472. }
  473. // End call triggers
  474. }
  475. if (empty($error)) {
  476. $this->db->commit();
  477. return 1;
  478. } else {
  479. $this->db->rollback();
  480. $this->error = $this->db->error();
  481. return -2;
  482. }
  483. } else {
  484. $this->db->rollback();
  485. $this->error = $this->db->error();
  486. return -1;
  487. }
  488. }
  489. /**
  490. * Load an object from database
  491. *
  492. * @param int $id Id {@min 1}
  493. * @param string $ref Ref {@name ref}
  494. * @return int <0 if KO, >0 if OK
  495. */
  496. public function fetch($id, $ref = '')
  497. {
  498. global $conf;
  499. $sql = "SELECT d.rowid, d.entity, d.ref, d.note_public, d.note_private,"; // DEFAULT
  500. $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS
  501. $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS
  502. $sql .= " d.total_ht, d.total_ttc, d.total_tva,";
  503. $sql .= " d.localtax1 as total_localtax1, d.localtax2 as total_localtax2,";
  504. $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime)
  505. $sql .= " d.fk_user_creat, d.fk_user_author, d.fk_user_modif, d.fk_user_validator,";
  506. $sql .= " d.fk_user_valid, d.fk_user_approve,";
  507. $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid";
  508. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d";
  509. if ($ref) {
  510. $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'";
  511. } else {
  512. $sql .= " WHERE d.rowid = ".((int) $id);
  513. }
  514. //$sql.= $restrict;
  515. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  516. $resql = $this->db->query($sql);
  517. if ($resql) {
  518. $obj = $this->db->fetch_object($resql);
  519. if ($obj) {
  520. $this->id = $obj->rowid;
  521. $this->ref = $obj->ref;
  522. $this->entity = $obj->entity;
  523. $this->total_ht = $obj->total_ht;
  524. $this->total_tva = $obj->total_tva;
  525. $this->total_ttc = $obj->total_ttc;
  526. $this->localtax1 = $obj->total_localtax1; // For backward compatibility
  527. $this->localtax2 = $obj->total_localtax2; // For backward compatibility
  528. $this->total_localtax1 = $obj->total_localtax1;
  529. $this->total_localtax2 = $obj->total_localtax2;
  530. $this->note_public = $obj->note_public;
  531. $this->note_private = $obj->note_private;
  532. $this->detail_refuse = $obj->detail_refuse;
  533. $this->detail_cancel = $obj->detail_cancel;
  534. $this->date_debut = $this->db->jdate($obj->date_debut);
  535. $this->date_fin = $this->db->jdate($obj->date_fin);
  536. $this->date_valid = $this->db->jdate($obj->date_valid);
  537. $this->date_approve = $this->db->jdate($obj->date_approve);
  538. $this->date_create = $this->db->jdate($obj->date_create);
  539. $this->date_modif = $this->db->jdate($obj->date_modif);
  540. $this->date_refuse = $this->db->jdate($obj->date_refuse);
  541. $this->date_cancel = $this->db->jdate($obj->date_cancel);
  542. $this->fk_user_creat = $obj->fk_user_creat;
  543. $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
  544. $this->fk_user_modif = $obj->fk_user_modif;
  545. $this->fk_user_validator = $obj->fk_user_validator;
  546. $this->fk_user_valid = $obj->fk_user_valid;
  547. $this->fk_user_refuse = $obj->fk_user_refuse;
  548. $this->fk_user_cancel = $obj->fk_user_cancel;
  549. $this->fk_user_approve = $obj->fk_user_approve;
  550. $user_author = new User($this->db);
  551. if ($this->fk_user_author > 0) {
  552. $user_author->fetch($this->fk_user_author);
  553. }
  554. $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname);
  555. $user_approver = new User($this->db);
  556. if ($this->fk_user_approve > 0) {
  557. $user_approver->fetch($this->fk_user_approve);
  558. } elseif ($this->fk_user_validator > 0) {
  559. $user_approver->fetch($this->fk_user_validator); // For backward compatibility
  560. }
  561. $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname);
  562. $this->fk_statut = $obj->status; // deprecated
  563. $this->status = $obj->status;
  564. $this->fk_c_paiement = $obj->fk_c_paiement;
  565. $this->paid = $obj->paid;
  566. if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED) {
  567. $user_valid = new User($this->db);
  568. if ($this->fk_user_valid > 0) {
  569. $user_valid->fetch($this->fk_user_valid);
  570. }
  571. $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname);
  572. }
  573. $this->fetch_optionals();
  574. $result = $this->fetch_lines();
  575. return $result;
  576. } else {
  577. return 0;
  578. }
  579. } else {
  580. $this->error = $this->db->lasterror();
  581. return -1;
  582. }
  583. }
  584. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  585. /**
  586. * Classify the expense report as paid
  587. *
  588. * @deprecated
  589. * @see setPaid()
  590. * @param int $id Id of expense report
  591. * @param user $fuser User making change
  592. * @param int $notrigger Disable triggers
  593. * @return int <0 if KO, >0 if OK
  594. */
  595. public function set_paid($id, $fuser, $notrigger = 0)
  596. {
  597. // phpcs:enable
  598. dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
  599. return $this->setPaid($id, $fuser, $notrigger);
  600. }
  601. /**
  602. * Classify the expense report as paid
  603. *
  604. * @param int $id Id of expense report
  605. * @param user $fuser User making change
  606. * @param int $notrigger Disable triggers
  607. * @return int <0 if KO, >0 if OK
  608. */
  609. public function setPaid($id, $fuser, $notrigger = 0)
  610. {
  611. $error = 0;
  612. $this->db->begin();
  613. $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport";
  614. $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1";
  615. $sql .= " WHERE rowid = ".((int) $id)." AND fk_statut = ".self::STATUS_APPROVED;
  616. dol_syslog(get_class($this)."::set_paid", LOG_DEBUG);
  617. $resql = $this->db->query($sql);
  618. if ($resql) {
  619. if ($this->db->affected_rows($resql)) {
  620. if (!$notrigger) {
  621. // Call trigger
  622. $result = $this->call_trigger('EXPENSE_REPORT_PAID', $fuser);
  623. if ($result < 0) {
  624. $error++;
  625. }
  626. // End call triggers
  627. }
  628. if (empty($error)) {
  629. $this->db->commit();
  630. return 1;
  631. } else {
  632. $this->db->rollback();
  633. $this->error = $this->db->error();
  634. return -2;
  635. }
  636. } else {
  637. $this->db->commit();
  638. return 0;
  639. }
  640. } else {
  641. $this->db->rollback();
  642. dol_print_error($this->db);
  643. return -1;
  644. }
  645. }
  646. /**
  647. * Returns the label status
  648. *
  649. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  650. * @return string Label
  651. */
  652. public function getLibStatut($mode = 0)
  653. {
  654. return $this->LibStatut($this->status, $mode);
  655. }
  656. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  657. /**
  658. * Returns the label of a status
  659. *
  660. * @param int $status ID status
  661. * @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
  662. * @return string Label
  663. */
  664. public function LibStatut($status, $mode = 0)
  665. {
  666. // phpcs:enable
  667. global $langs;
  668. $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]);
  669. $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]);
  670. $statusType = $this->statuts_logo[$status];
  671. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
  672. }
  673. /**
  674. * Load information on object
  675. *
  676. * @param int $id Id of object
  677. * @return void
  678. */
  679. public function info($id)
  680. {
  681. global $conf;
  682. $sql = "SELECT f.rowid,";
  683. $sql .= " f.date_create as datec,";
  684. $sql .= " f.tms as date_modification,";
  685. $sql .= " f.date_valid as datev,";
  686. $sql .= " f.date_approve as datea,";
  687. $sql .= " f.fk_user_creat as fk_user_creation,";
  688. $sql .= " f.fk_user_author as fk_user_author,";
  689. $sql .= " f.fk_user_modif as fk_user_modification,";
  690. $sql .= " f.fk_user_valid,";
  691. $sql .= " f.fk_user_approve";
  692. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f";
  693. $sql .= " WHERE f.rowid = ".((int) $id);
  694. $sql .= " AND f.entity = ".$conf->entity;
  695. $resql = $this->db->query($sql);
  696. if ($resql) {
  697. if ($this->db->num_rows($resql)) {
  698. $obj = $this->db->fetch_object($resql);
  699. $this->id = $obj->rowid;
  700. $this->date_creation = $this->db->jdate($obj->datec);
  701. $this->date_modification = $this->db->jdate($obj->date_modification);
  702. $this->date_validation = $this->db->jdate($obj->datev);
  703. $this->date_approbation = $this->db->jdate($obj->datea);
  704. $cuser = new User($this->db);
  705. $cuser->fetch($obj->fk_user_author);
  706. $this->user_creation = $cuser;
  707. if ($obj->fk_user_creation) {
  708. $cuser = new User($this->db);
  709. $cuser->fetch($obj->fk_user_creation);
  710. $this->user_creation = $cuser;
  711. }
  712. if ($obj->fk_user_valid) {
  713. $vuser = new User($this->db);
  714. $vuser->fetch($obj->fk_user_valid);
  715. $this->user_validation = $vuser;
  716. }
  717. if ($obj->fk_user_modification) {
  718. $muser = new User($this->db);
  719. $muser->fetch($obj->fk_user_modification);
  720. $this->user_modification = $muser;
  721. }
  722. if ($obj->fk_user_approve) {
  723. $auser = new User($this->db);
  724. $auser->fetch($obj->fk_user_approve);
  725. $this->user_approve = $auser;
  726. }
  727. }
  728. $this->db->free($resql);
  729. } else {
  730. dol_print_error($this->db);
  731. }
  732. }
  733. /**
  734. * Initialise an instance with random values.
  735. * Used to build previews or test instances.
  736. * id must be 0 if object instance is a specimen.
  737. *
  738. * @return void
  739. */
  740. public function initAsSpecimen()
  741. {
  742. global $user, $langs, $conf;
  743. $now = dol_now();
  744. // Initialise parametres
  745. $this->id = 0;
  746. $this->ref = 'SPECIMEN';
  747. $this->specimen = 1;
  748. $this->entity = 1;
  749. $this->date_create = $now;
  750. $this->date_debut = $now;
  751. $this->date_fin = $now;
  752. $this->date_valid = $now;
  753. $this->date_approve = $now;
  754. $type_fees_id = 2; // TF_TRIP
  755. $this->status = 5;
  756. $this->fk_statut = 5;
  757. $this->fk_user_author = $user->id;
  758. $this->fk_user_validator = $user->id;
  759. $this->fk_user_valid = $user->id;
  760. $this->fk_user_approve = $user->id;
  761. $this->note_private = 'Private note';
  762. $this->note_public = 'SPECIMEN';
  763. $nbp = 5;
  764. $xnbp = 0;
  765. while ($xnbp < $nbp) {
  766. $line = new ExpenseReportLine($this->db);
  767. $line->comments = $langs->trans("Comment")." ".$xnbp;
  768. $line->date = ($now - 3600 * (1 + $xnbp));
  769. $line->total_ht = 100;
  770. $line->total_tva = 20;
  771. $line->total_ttc = 120;
  772. $line->qty = 1;
  773. $line->vatrate = 20;
  774. $line->value_unit = 120;
  775. $line->fk_expensereport = 0;
  776. $line->type_fees_code = 'TRA';
  777. $line->fk_c_type_fees = $type_fees_id;
  778. $line->projet_ref = 'ABC';
  779. $this->lines[$xnbp] = $line;
  780. $xnbp++;
  781. $this->total_ht += $line->total_ht;
  782. $this->total_tva += $line->total_tva;
  783. $this->total_ttc += $line->total_ttc;
  784. }
  785. }
  786. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  787. /**
  788. * fetch_line_by_project
  789. *
  790. * @param int $projectid Project id
  791. * @param User $user User
  792. * @return int <0 if KO, >0 if OK
  793. */
  794. public function fetch_line_by_project($projectid, $user = '')
  795. {
  796. // phpcs:enable
  797. global $conf, $db, $langs;
  798. $langs->load('trips');
  799. if ($user->rights->expensereport->lire) {
  800. $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc";
  801. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de";
  802. $sql .= " WHERE de.fk_projet = ".((int) $projectid);
  803. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  804. $result = $this->db->query($sql);
  805. if ($result) {
  806. $num = $this->db->num_rows($result);
  807. $i = 0;
  808. $total_HT = 0;
  809. $total_TTC = 0;
  810. while ($i < $num) {
  811. $objp = $this->db->fetch_object($result);
  812. $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut as status";
  813. $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d";
  814. $sql2 .= " WHERE d.rowid = ".((int) $objp->fk_expensereport);
  815. $result2 = $this->db->query($sql2);
  816. $obj = $this->db->fetch_object($result2);
  817. $objp->fk_user_author = $obj->fk_user_author;
  818. $objp->ref = $obj->ref;
  819. $objp->fk_c_expensereport_status = $obj->status;
  820. $objp->rowid = $obj->rowid;
  821. $total_HT = $total_HT + $objp->total_ht;
  822. $total_TTC = $total_TTC + $objp->total_ttc;
  823. $author = new User($this->db);
  824. $author->fetch($objp->fk_user_author);
  825. print '<tr>';
  826. print '<td><a href="'.DOL_URL_ROOT.'/expensereport/card.php?id='.$objp->rowid.'">'.$objp->ref_num.'</a></td>';
  827. print '<td class="center">'.dol_print_date($objp->date, 'day').'</td>';
  828. print '<td>'.$author->getNomUrl(1).'</td>';
  829. print '<td>'.$objp->comments.'</td>';
  830. print '<td class="right">'.price($objp->total_ht).'</td>';
  831. print '<td class="right">'.price($objp->total_ttc).'</td>';
  832. print '<td class="right">';
  833. switch ($objp->fk_c_expensereport_status) {
  834. case 4:
  835. print img_picto($langs->trans('StatusOrderCanceled'), 'statut5');
  836. break;
  837. case 1:
  838. print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0');
  839. break;
  840. case 2:
  841. print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3');
  842. break;
  843. case 5:
  844. print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3');
  845. break;
  846. case 6:
  847. print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4');
  848. break;
  849. }
  850. /*
  851. if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
  852. if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
  853. if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1');
  854. if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3');
  855. if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
  856. if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6');
  857. */
  858. print '</td>';
  859. print '</tr>';
  860. $i++;
  861. }
  862. print '<tr class="liste_total"><td colspan="4">'.$langs->trans("Number").': '.$i.'</td>';
  863. print '<td class="right" width="100">'.$langs->trans("TotalHT").' : '.price($total_HT).'</td>';
  864. print '<td class="right" width="100">'.$langs->trans("TotalTTC").' : '.price($total_TTC).'</td>';
  865. print '<td>&nbsp;</td>';
  866. print '</tr>';
  867. } else {
  868. $this->error = $this->db->lasterror();
  869. return -1;
  870. }
  871. }
  872. }
  873. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  874. /**
  875. * fetch_lines
  876. *
  877. * @return int <0 if OK, >0 if KO
  878. */
  879. public function fetch_lines()
  880. {
  881. // phpcs:enable
  882. global $conf;
  883. $this->lines = array();
  884. $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,';
  885. $sql .= " de.".$this->fk_element.", de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project,";
  886. $sql .= ' de.tva_tx, de.vat_src_code,';
  887. $sql .= ' de.localtax1_tx, de.localtax2_tx, de.localtax1_type, de.localtax2_type,';
  888. $sql .= ' de.fk_ecm_files,';
  889. $sql .= ' de.total_ht, de.total_tva, de.total_ttc,';
  890. $sql .= ' de.total_localtax1, de.total_localtax2, de.rule_warning_message,';
  891. $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees, ctf.accountancy_code as accountancy_code_type_fees,';
  892. $sql .= ' p.ref as ref_projet, p.title as title_projet';
  893. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de';
  894. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id';
  895. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid';
  896. $sql .= " WHERE de.".$this->fk_element." = ".((int) $this->id);
  897. if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID)) {
  898. $sql .= ' ORDER BY de.rang ASC, de.rowid ASC';
  899. } else {
  900. $sql .= ' ORDER BY de.rang ASC, de.date ASC';
  901. }
  902. $resql = $this->db->query($sql);
  903. if ($resql) {
  904. $num = $this->db->num_rows($resql);
  905. $i = 0;
  906. while ($i < $num) {
  907. $objp = $this->db->fetch_object($resql);
  908. $deplig = new ExpenseReportLine($this->db);
  909. $deplig->rowid = $objp->rowid;
  910. $deplig->id = $objp->rowid;
  911. $deplig->comments = $objp->comments;
  912. $deplig->qty = $objp->qty;
  913. $deplig->value_unit = $objp->value_unit;
  914. $deplig->date = $objp->date;
  915. $deplig->dates = $this->db->jdate($objp->date);
  916. $deplig->fk_expensereport = $objp->fk_expensereport;
  917. $deplig->fk_c_type_fees = $objp->fk_c_type_fees;
  918. $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
  919. $deplig->fk_projet = $objp->fk_project; // deprecated
  920. $deplig->fk_project = $objp->fk_project;
  921. $deplig->fk_ecm_files = $objp->fk_ecm_files;
  922. $deplig->total_ht = $objp->total_ht;
  923. $deplig->total_tva = $objp->total_tva;
  924. $deplig->total_ttc = $objp->total_ttc;
  925. $deplig->total_localtax1 = $objp->total_localtax1;
  926. $deplig->total_localtax2 = $objp->total_localtax2;
  927. $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees;
  928. $deplig->type_fees_libelle = $objp->libelle_type_fees;
  929. $deplig->type_fees_accountancy_code = $objp->accountancy_code_type_fees;
  930. $deplig->tva_tx = $objp->tva_tx;
  931. $deplig->vatrate = $objp->tva_tx;
  932. $deplig->vat_src_code = $objp->vat_src_code;
  933. $deplig->localtax1_tx = $objp->localtax1_tx;
  934. $deplig->localtax2_tx = $objp->localtax2_tx;
  935. $deplig->localtax1_type = $objp->localtax1_type;
  936. $deplig->localtax2_type = $objp->localtax2_type;
  937. $deplig->projet_ref = $objp->ref_projet;
  938. $deplig->projet_title = $objp->title_projet;
  939. $deplig->rule_warning_message = $objp->rule_warning_message;
  940. $deplig->rang = $objp->rang;
  941. $this->lines[$i] = $deplig;
  942. $i++;
  943. }
  944. $this->db->free($resql);
  945. return 1;
  946. } else {
  947. $this->error = $this->db->lasterror();
  948. dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR);
  949. return -3;
  950. }
  951. }
  952. /**
  953. * Delete object in database
  954. *
  955. * @param User $user User that delete
  956. * @param bool $notrigger false=launch triggers after, true=disable triggers
  957. * @return int <0 if KO, >0 if OK
  958. */
  959. public function delete(User $user = null, $notrigger = false)
  960. {
  961. global $conf;
  962. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  963. $error = 0;
  964. $this->db->begin();
  965. if (!$notrigger) {
  966. // Call trigger
  967. $result = $this->call_trigger('EXPENSE_REPORT_DELETE', $user);
  968. if ($result < 0) {
  969. $error++;
  970. }
  971. // End call triggers
  972. }
  973. // Delete extrafields of lines and lines
  974. if (!$error && !empty($this->table_element_line)) {
  975. $tabletodelete = $this->table_element_line;
  976. //$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).")";
  977. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
  978. if (!$this->db->query($sql)) {
  979. $error++;
  980. $this->error = $this->db->lasterror();
  981. $this->errors[] = $this->error;
  982. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  983. }
  984. }
  985. if (!$error) {
  986. // Delete linked object
  987. $res = $this->deleteObjectLinked();
  988. if ($res < 0) {
  989. $error++;
  990. }
  991. }
  992. if (!$error) {
  993. // Delete linked contacts
  994. $res = $this->delete_linked_contact();
  995. if ($res < 0) {
  996. $error++;
  997. }
  998. }
  999. // Removed extrafields of object
  1000. if (!$error) {
  1001. $result = $this->deleteExtraFields();
  1002. if ($result < 0) {
  1003. $error++;
  1004. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  1005. }
  1006. }
  1007. // Delete main record
  1008. if (!$error) {
  1009. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
  1010. $res = $this->db->query($sql);
  1011. if (!$res) {
  1012. $error++;
  1013. $this->error = $this->db->lasterror();
  1014. $this->errors[] = $this->error;
  1015. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  1016. }
  1017. }
  1018. // Delete record into ECM index and physically
  1019. if (!$error) {
  1020. $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
  1021. if (!$res) {
  1022. $error++;
  1023. }
  1024. }
  1025. if (!$error) {
  1026. // We remove directory
  1027. $ref = dol_sanitizeFileName($this->ref);
  1028. if ($conf->expensereport->multidir_output[$this->entity] && !empty($this->ref)) {
  1029. $dir = $conf->expensereport->multidir_output[$this->entity]."/".$ref;
  1030. $file = $dir."/".$ref.".pdf";
  1031. if (file_exists($file)) {
  1032. dol_delete_preview($this);
  1033. if (!dol_delete_file($file, 0, 0, 0, $this)) {
  1034. $this->error = 'ErrorFailToDeleteFile';
  1035. $this->errors[] = $this->error;
  1036. $this->db->rollback();
  1037. return 0;
  1038. }
  1039. }
  1040. if (file_exists($dir)) {
  1041. $res = @dol_delete_dir_recursive($dir);
  1042. if (!$res) {
  1043. $this->error = 'ErrorFailToDeleteDir';
  1044. $this->errors[] = $this->error;
  1045. $this->db->rollback();
  1046. return 0;
  1047. }
  1048. }
  1049. }
  1050. }
  1051. if (!$error) {
  1052. dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
  1053. $this->db->commit();
  1054. return 1;
  1055. } else {
  1056. $this->db->rollback();
  1057. return -1;
  1058. }
  1059. }
  1060. /**
  1061. * Set to status validate
  1062. *
  1063. * @param User $fuser User
  1064. * @param int $notrigger Disable triggers
  1065. * @return int <0 if KO, 0 if nothing done, >0 if OK
  1066. */
  1067. public function setValidate($fuser, $notrigger = 0)
  1068. {
  1069. global $conf, $langs, $user;
  1070. $error = 0;
  1071. $now = dol_now();
  1072. // Protection
  1073. if ($this->status == self::STATUS_VALIDATED) {
  1074. dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
  1075. return 0;
  1076. }
  1077. $this->date_valid = $now; // Required for the getNextNum later.
  1078. // Define new ref
  1079. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  1080. $num = $this->getNextNumRef();
  1081. } else {
  1082. $num = $this->ref;
  1083. }
  1084. if (empty($num) || $num < 0) {
  1085. return -1;
  1086. }
  1087. $this->newref = dol_sanitizeFileName($num);
  1088. $this->db->begin();
  1089. // Validate
  1090. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1091. $sql .= " SET ref = '".$this->db->escape($num)."',";
  1092. $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
  1093. $sql .= " date_valid='".$this->db->idate($this->date_valid)."',";
  1094. $sql .= " fk_user_valid = ".$user->id;
  1095. $sql .= " WHERE rowid = ".((int) $this->id);
  1096. $resql = $this->db->query($sql);
  1097. if ($resql) {
  1098. if (!$error && !$notrigger) {
  1099. // Call trigger
  1100. $result = $this->call_trigger('EXPENSE_REPORT_VALIDATE', $fuser);
  1101. if ($result < 0) {
  1102. $error++;
  1103. }
  1104. // End call triggers
  1105. }
  1106. if (!$error) {
  1107. $this->oldref = $this->ref;
  1108. // Rename directory if dir was a temporary ref
  1109. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  1110. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1111. // Now we rename also files into index
  1112. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expensereport/".$this->db->escape($this->newref)."'";
  1113. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  1114. $resql = $this->db->query($sql);
  1115. if (!$resql) {
  1116. $error++; $this->error = $this->db->lasterror();
  1117. }
  1118. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  1119. $oldref = dol_sanitizeFileName($this->ref);
  1120. $newref = dol_sanitizeFileName($num);
  1121. $dirsource = $conf->expensereport->dir_output.'/'.$oldref;
  1122. $dirdest = $conf->expensereport->dir_output.'/'.$newref;
  1123. if (!$error && file_exists($dirsource)) {
  1124. dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest);
  1125. if (@rename($dirsource, $dirdest)) {
  1126. dol_syslog("Rename ok");
  1127. // Rename docs starting with $oldref with $newref
  1128. $listoffiles = dol_dir_list($conf->expensereport->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  1129. foreach ($listoffiles as $fileentry) {
  1130. $dirsource = $fileentry['name'];
  1131. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  1132. $dirsource = $fileentry['path'].'/'.$dirsource;
  1133. $dirdest = $fileentry['path'].'/'.$dirdest;
  1134. @rename($dirsource, $dirdest);
  1135. }
  1136. }
  1137. }
  1138. }
  1139. }
  1140. // Set new ref and current status
  1141. if (!$error) {
  1142. $this->ref = $num;
  1143. $this->status = self::STATUS_VALIDATED;
  1144. }
  1145. if (empty($error)) {
  1146. $this->db->commit();
  1147. return 1;
  1148. } else {
  1149. $this->db->rollback();
  1150. $this->error = $this->db->error();
  1151. return -2;
  1152. }
  1153. } else {
  1154. $this->db->rollback();
  1155. $this->error = $this->db->lasterror();
  1156. return -1;
  1157. }
  1158. }
  1159. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1160. /**
  1161. * set_save_from_refuse
  1162. *
  1163. * @param User $fuser User
  1164. * @return int <0 if KO, >0 if OK
  1165. */
  1166. public function set_save_from_refuse($fuser)
  1167. {
  1168. // phpcs:enable
  1169. global $conf, $langs;
  1170. // Sélection de la date de début de la NDF
  1171. $sql = 'SELECT date_debut';
  1172. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
  1173. $sql .= " WHERE rowid = ".((int) $this->id);
  1174. $result = $this->db->query($sql);
  1175. $objp = $this->db->fetch_object($result);
  1176. $this->date_debut = $this->db->jdate($objp->date_debut);
  1177. if ($this->status != self::STATUS_VALIDATED) {
  1178. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1179. $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
  1180. $sql .= " WHERE rowid = ".((int) $this->id);
  1181. dol_syslog(get_class($this)."::set_save_from_refuse", LOG_DEBUG);
  1182. if ($this->db->query($sql)) {
  1183. return 1;
  1184. } else {
  1185. $this->error = $this->db->lasterror();
  1186. return -1;
  1187. }
  1188. } else {
  1189. dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING);
  1190. }
  1191. }
  1192. /**
  1193. * Set status to approved
  1194. *
  1195. * @param User $fuser User
  1196. * @param int $notrigger Disable triggers
  1197. * @return int <0 if KO, 0 if nothing done, >0 if OK
  1198. */
  1199. public function setApproved($fuser, $notrigger = 0)
  1200. {
  1201. $now = dol_now();
  1202. $error = 0;
  1203. // date approval
  1204. $this->date_approve = $now;
  1205. if ($this->status != self::STATUS_APPROVED) {
  1206. $this->db->begin();
  1207. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1208. $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".((int) $fuser->id).",";
  1209. $sql .= " date_approve='".$this->db->idate($this->date_approve)."'";
  1210. $sql .= " WHERE rowid = ".((int) $this->id);
  1211. if ($this->db->query($sql)) {
  1212. if (!$notrigger) {
  1213. // Call trigger
  1214. $result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser);
  1215. if ($result < 0) {
  1216. $error++;
  1217. }
  1218. // End call triggers
  1219. }
  1220. if (empty($error)) {
  1221. $this->db->commit();
  1222. return 1;
  1223. } else {
  1224. $this->db->rollback();
  1225. $this->error = $this->db->error();
  1226. return -2;
  1227. }
  1228. } else {
  1229. $this->db->rollback();
  1230. $this->error = $this->db->lasterror();
  1231. return -1;
  1232. }
  1233. } else {
  1234. dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING);
  1235. }
  1236. return 0;
  1237. }
  1238. /**
  1239. * setDeny
  1240. *
  1241. * @param User $fuser User
  1242. * @param string $details Details
  1243. * @param int $notrigger Disable triggers
  1244. * @return int
  1245. */
  1246. public function setDeny($fuser, $details, $notrigger = 0)
  1247. {
  1248. $now = dol_now();
  1249. $error = 0;
  1250. // date de refus
  1251. if ($this->status != self::STATUS_REFUSED) {
  1252. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1253. $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".((int) $fuser->id).",";
  1254. $sql .= " date_refuse='".$this->db->idate($now)."',";
  1255. $sql .= " detail_refuse='".$this->db->escape($details)."',";
  1256. $sql .= " fk_user_approve = NULL";
  1257. $sql .= " WHERE rowid = ".((int) $this->id);
  1258. if ($this->db->query($sql)) {
  1259. $this->fk_statut = 99; // deprecated
  1260. $this->status = 99;
  1261. $this->fk_user_refuse = $fuser->id;
  1262. $this->detail_refuse = $details;
  1263. $this->date_refuse = $now;
  1264. if (!$notrigger) {
  1265. // Call trigger
  1266. $result = $this->call_trigger('EXPENSE_REPORT_DENY', $fuser);
  1267. if ($result < 0) {
  1268. $error++;
  1269. }
  1270. // End call triggers
  1271. }
  1272. if (empty($error)) {
  1273. $this->db->commit();
  1274. return 1;
  1275. } else {
  1276. $this->db->rollback();
  1277. $this->error = $this->db->error();
  1278. return -2;
  1279. }
  1280. } else {
  1281. $this->db->rollback();
  1282. $this->error = $this->db->lasterror();
  1283. return -1;
  1284. }
  1285. } else {
  1286. dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING);
  1287. }
  1288. }
  1289. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1290. /**
  1291. * set_unpaid
  1292. *
  1293. * @deprecated
  1294. * @see setUnpaid()
  1295. * @param User $fuser User
  1296. * @param int $notrigger Disable triggers
  1297. * @return int <0 if KO, >0 if OK
  1298. */
  1299. public function set_unpaid($fuser, $notrigger = 0)
  1300. {
  1301. // phpcs:enable
  1302. dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
  1303. return $this->setUnpaid($fuser, $notrigger);
  1304. }
  1305. /**
  1306. * set_unpaid
  1307. *
  1308. * @param User $fuser User
  1309. * @param int $notrigger Disable triggers
  1310. * @return int <0 if KO, >0 if OK
  1311. */
  1312. public function setUnpaid($fuser, $notrigger = 0)
  1313. {
  1314. $error = 0;
  1315. if ($this->paid) {
  1316. $this->db->begin();
  1317. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1318. $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED;
  1319. $sql .= " WHERE rowid = ".((int) $this->id);
  1320. dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
  1321. if ($this->db->query($sql)) {
  1322. if (!$notrigger) {
  1323. // Call trigger
  1324. $result = $this->call_trigger('EXPENSE_REPORT_UNPAID', $fuser);
  1325. if ($result < 0) {
  1326. $error++;
  1327. }
  1328. // End call triggers
  1329. }
  1330. if (empty($error)) {
  1331. $this->db->commit();
  1332. return 1;
  1333. } else {
  1334. $this->db->rollback();
  1335. $this->error = $this->db->error();
  1336. return -2;
  1337. }
  1338. } else {
  1339. $this->db->rollback();
  1340. $this->error = $this->db->error();
  1341. return -1;
  1342. }
  1343. } else {
  1344. dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING);
  1345. }
  1346. }
  1347. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1348. /**
  1349. * set_cancel
  1350. *
  1351. * @param User $fuser User
  1352. * @param string $detail Detail
  1353. * @param int $notrigger Disable triggers
  1354. * @return int <0 if KO, >0 if OK
  1355. */
  1356. public function set_cancel($fuser, $detail, $notrigger = 0)
  1357. {
  1358. // phpcs:enable
  1359. $error = 0;
  1360. $this->date_cancel = $this->db->idate(dol_now());
  1361. if ($this->status != self::STATUS_CANCELED) {
  1362. $this->db->begin();
  1363. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1364. $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".((int) $fuser->id);
  1365. $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'";
  1366. $sql .= " ,detail_cancel='".$this->db->escape($detail)."'";
  1367. $sql .= " WHERE rowid = ".((int) $this->id);
  1368. dol_syslog(get_class($this)."::set_cancel", LOG_DEBUG);
  1369. if ($this->db->query($sql)) {
  1370. if (!$notrigger) {
  1371. // Call trigger
  1372. $result = $this->call_trigger('EXPENSE_REPORT_CANCEL', $fuser);
  1373. if ($result < 0) {
  1374. $error++;
  1375. }
  1376. // End call triggers
  1377. }
  1378. if (empty($error)) {
  1379. $this->db->commit();
  1380. return 1;
  1381. } else {
  1382. $this->db->rollback();
  1383. $this->error = $this->db->error();
  1384. return -2;
  1385. }
  1386. } else {
  1387. $this->db->rollback();
  1388. $this->error = $this->db->error();
  1389. return -1;
  1390. }
  1391. } else {
  1392. dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING);
  1393. }
  1394. }
  1395. /**
  1396. * Return next reference of expense report not already used
  1397. *
  1398. * @return string free ref
  1399. */
  1400. public function getNextNumRef()
  1401. {
  1402. global $langs, $conf;
  1403. $langs->load("trips");
  1404. if (!empty($conf->global->EXPENSEREPORT_ADDON)) {
  1405. $mybool = false;
  1406. $file = $conf->global->EXPENSEREPORT_ADDON.".php";
  1407. $classname = $conf->global->EXPENSEREPORT_ADDON;
  1408. // Include file with class
  1409. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  1410. foreach ($dirmodels as $reldir) {
  1411. $dir = dol_buildpath($reldir."core/modules/expensereport/");
  1412. // Load file with numbering class (if found)
  1413. $mybool |= @include_once $dir.$file;
  1414. }
  1415. if ($mybool === false) {
  1416. dol_print_error('', "Failed to include file ".$file);
  1417. return '';
  1418. }
  1419. $obj = new $classname();
  1420. $numref = $obj->getNextValue($this);
  1421. if ($numref != "") {
  1422. return $numref;
  1423. } else {
  1424. $this->error = $obj->error;
  1425. $this->errors = $obj->errors;
  1426. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  1427. return -1;
  1428. }
  1429. } else {
  1430. $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined";
  1431. return -2;
  1432. }
  1433. }
  1434. /**
  1435. * Return clicable name (with picto eventually)
  1436. *
  1437. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1438. * @param string $option Where point the link ('', 'document', ..)
  1439. * @param int $max Max length of shown ref
  1440. * @param int $short 1=Return just URL
  1441. * @param string $moretitle Add more text to title tooltip
  1442. * @param int $notooltip 1=Disable tooltip
  1443. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1444. * @return string String with URL
  1445. */
  1446. public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
  1447. {
  1448. global $langs, $conf, $hookmanager;
  1449. $result = '';
  1450. $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id;
  1451. if ($short) {
  1452. return $url;
  1453. }
  1454. $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ExpenseReport").'</u>';
  1455. if (isset($this->status)) {
  1456. $label .= ' '.$this->getLibStatut(5);
  1457. }
  1458. if (!empty($this->ref)) {
  1459. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1460. }
  1461. if (!empty($this->total_ht)) {
  1462. $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  1463. }
  1464. if (!empty($this->total_tva)) {
  1465. $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  1466. }
  1467. if (!empty($this->total_ttc)) {
  1468. $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  1469. }
  1470. if ($moretitle) {
  1471. $label .= ' - '.$moretitle;
  1472. }
  1473. if ($option != 'nolink') {
  1474. // Add param to save lastsearch_values or not
  1475. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1476. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1477. $add_save_lastsearch_values = 1;
  1478. }
  1479. if ($add_save_lastsearch_values) {
  1480. $url .= '&save_lastsearch_values=1';
  1481. }
  1482. }
  1483. $ref = $this->ref;
  1484. if (empty($ref)) {
  1485. $ref = $this->id;
  1486. }
  1487. $linkclose = '';
  1488. if (empty($notooltip)) {
  1489. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1490. $label = $langs->trans("ShowExpenseReport");
  1491. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1492. }
  1493. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1494. $linkclose .= ' class="classfortooltip"';
  1495. }
  1496. $linkstart = '<a href="'.$url.'"';
  1497. $linkstart .= $linkclose.'>';
  1498. $linkend = '</a>';
  1499. $result .= $linkstart;
  1500. if ($withpicto) {
  1501. $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1502. }
  1503. if ($withpicto != 2) {
  1504. $result .= ($max ? dol_trunc($ref, $max) : $ref);
  1505. }
  1506. $result .= $linkend;
  1507. global $action;
  1508. $hookmanager->initHooks(array($this->element . 'dao'));
  1509. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1510. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1511. if ($reshook > 0) {
  1512. $result = $hookmanager->resPrint;
  1513. } else {
  1514. $result .= $hookmanager->resPrint;
  1515. }
  1516. return $result;
  1517. }
  1518. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1519. /**
  1520. * Update total of an expense report when you add a line.
  1521. *
  1522. * @param string $ligne_total_ht Amount without taxes
  1523. * @param string $ligne_total_tva Amount of all taxes
  1524. * @return void
  1525. */
  1526. public function update_totaux_add($ligne_total_ht, $ligne_total_tva)
  1527. {
  1528. // phpcs:enable
  1529. $this->total_ht = $this->total_ht + $ligne_total_ht;
  1530. $this->total_tva = $this->total_tva + $ligne_total_tva;
  1531. $this->total_ttc = $this->total_ht + $this->total_tva;
  1532. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
  1533. $sql .= " total_ht = ".$this->total_ht;
  1534. $sql .= " , total_ttc = ".$this->total_ttc;
  1535. $sql .= " , total_tva = ".$this->total_tva;
  1536. $sql .= " WHERE rowid = ".((int) $this->id);
  1537. $result = $this->db->query($sql);
  1538. if ($result) {
  1539. return 1;
  1540. } else {
  1541. $this->error = $this->db->error();
  1542. return -1;
  1543. }
  1544. }
  1545. /**
  1546. * Add expense report line
  1547. *
  1548. * @param float $qty Qty
  1549. * @param double $up Unit price (price with tax)
  1550. * @param int $fk_c_type_fees Type payment
  1551. * @param string $vatrate Vat rate (Can be '10' or '10 (ABC)')
  1552. * @param string $date Date
  1553. * @param string $comments Description
  1554. * @param int $fk_project Project id
  1555. * @param int $fk_c_exp_tax_cat Car category id
  1556. * @param int $type Type line
  1557. * @param int $fk_ecm_files Id of ECM file to link to this expensereport line
  1558. * @return int <0 if KO, >0 if OK
  1559. */
  1560. public function addline($qty = 0, $up = 0, $fk_c_type_fees = 0, $vatrate = 0, $date = '', $comments = '', $fk_project = 0, $fk_c_exp_tax_cat = 0, $type = 0, $fk_ecm_files = 0)
  1561. {
  1562. global $conf, $langs, $mysoc;
  1563. dol_syslog(get_class($this)."::addline qty=$qty, up=$up, fk_c_type_fees=$fk_c_type_fees, vatrate=$vatrate, date=$date, fk_project=$fk_project, type=$type, comments=$comments", LOG_DEBUG);
  1564. if ($this->status == self::STATUS_DRAFT) {
  1565. if (empty($qty)) {
  1566. $qty = 0;
  1567. }
  1568. if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) {
  1569. $fk_c_type_fees = 0;
  1570. }
  1571. if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) {
  1572. $fk_c_exp_tax_cat = 0;
  1573. }
  1574. if (empty($vatrate) || $vatrate < 0) {
  1575. $vatrate = 0;
  1576. }
  1577. if (empty($date)) {
  1578. $date = '';
  1579. }
  1580. if (empty($fk_project)) {
  1581. $fk_project = 0;
  1582. }
  1583. $qty = price2num($qty);
  1584. if (!preg_match('/\s*\((.*)\)/', $vatrate)) {
  1585. $vatrate = price2num($vatrate); // $txtva can have format '5.0 (XXX)' or '5'
  1586. }
  1587. $up = price2num($up);
  1588. $this->db->begin();
  1589. $this->line = new ExpenseReportLine($this->db);
  1590. // We don't know seller and buyer for expense reports
  1591. $seller = $mysoc; // We use same than current company (expense report are often done in same country)
  1592. $seller->tva_assuj = 1; // Most seller uses vat
  1593. $buyer = new Societe($this->db);
  1594. $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
  1595. $vat_src_code = '';
  1596. $reg = array();
  1597. if (preg_match('/\s*\((.*)\)/', $vatrate, $reg)) {
  1598. $vat_src_code = $reg[1];
  1599. $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
  1600. }
  1601. $vatrate = preg_replace('/\*/', '', $vatrate);
  1602. $tmp = calcul_price_total($qty, $up, 0, $vatrate, -1, -1, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
  1603. $this->line->value_unit = $up;
  1604. $this->line->vat_src_code = $vat_src_code;
  1605. $this->line->vatrate = price2num($vatrate);
  1606. $this->line->localtax1_tx = $localtaxes_type[1];
  1607. $this->line->localtax2_tx = $localtaxes_type[3];
  1608. $this->line->localtax1_type = $localtaxes_type[0];
  1609. $this->line->localtax2_type = $localtaxes_type[2];
  1610. $this->line->total_ttc = $tmp[2];
  1611. $this->line->total_ht = $tmp[0];
  1612. $this->line->total_tva = $tmp[1];
  1613. $this->line->total_localtax1 = $tmp[9];
  1614. $this->line->total_localtax2 = $tmp[10];
  1615. $this->line->fk_expensereport = $this->id;
  1616. $this->line->qty = $qty;
  1617. $this->line->date = $date;
  1618. $this->line->fk_c_type_fees = $fk_c_type_fees;
  1619. $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
  1620. $this->line->comments = $comments;
  1621. $this->line->fk_projet = $fk_project; // deprecated
  1622. $this->line->fk_project = $fk_project;
  1623. $this->line->fk_ecm_files = $fk_ecm_files;
  1624. $this->applyOffset();
  1625. $this->checkRules($type, $seller);
  1626. $result = $this->line->insert(0, true);
  1627. if ($result > 0) {
  1628. $result = $this->update_price(1); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
  1629. if ($result > 0) {
  1630. $this->db->commit();
  1631. return $this->line->id;
  1632. } else {
  1633. $this->db->rollback();
  1634. return -1;
  1635. }
  1636. } else {
  1637. $this->error = $this->line->error;
  1638. dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
  1639. $this->db->rollback();
  1640. return -2;
  1641. }
  1642. } else {
  1643. dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR);
  1644. $this->error = 'ErrorExpenseNotDraft';
  1645. return -3;
  1646. }
  1647. }
  1648. /**
  1649. * Check constraint of rules and update price if needed
  1650. *
  1651. * @param int $type Type of line
  1652. * @param string $seller Seller, but actually he is unknown
  1653. * @return true or false
  1654. */
  1655. public function checkRules($type = 0, $seller = '')
  1656. {
  1657. global $user, $conf, $db, $langs, $mysoc;
  1658. $langs->load('trips');
  1659. // We don't know seller and buyer for expense reports
  1660. if (!is_object($seller)) {
  1661. $seller = $mysoc; // We use same than current company (expense report are often done in same country)
  1662. $seller->tva_assuj = 1; // Most seller uses vat
  1663. }
  1664. $expensereportrule = new ExpenseReportRule($db);
  1665. $rulestocheck = $expensereportrule->getAllRule($this->line->fk_c_type_fees, $this->line->date, $this->fk_user_author);
  1666. $violation = 0;
  1667. $rule_warning_message_tab = array();
  1668. $current_total_ttc = $this->line->total_ttc;
  1669. $new_current_total_ttc = $this->line->total_ttc;
  1670. // check if one is violated
  1671. foreach ($rulestocheck as $rule) {
  1672. if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) {
  1673. $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type);
  1674. } else {
  1675. $amount_to_test = $current_total_ttc; // EX_EXP
  1676. }
  1677. $amount_to_test = $amount_to_test - $current_total_ttc + $new_current_total_ttc; // if amount as been modified by a previous rule
  1678. if ($amount_to_test > $rule->amount) {
  1679. $violation++;
  1680. if ($rule->restrictive) {
  1681. $this->error = 'ExpenseReportConstraintViolationError';
  1682. $this->errors[] = $this->error;
  1683. $new_current_total_ttc -= $amount_to_test - $rule->amount; // ex, entered 16€, limit 12€, subtracts 4€;
  1684. $rule_warning_message_tab[] = $langs->trans('ExpenseReportConstraintViolationError', $rule->id, price($amount_to_test, 0, $langs, 1, -1, -1, $conf->currency), price($rule->amount, 0, $langs, 1, -1, -1, $conf->currency));
  1685. } else {
  1686. $this->error = 'ExpenseReportConstraintViolationWarning';
  1687. $this->errors[] = $this->error;
  1688. $rule_warning_message_tab[] = $langs->trans('ExpenseReportConstraintViolationWarning', $rule->id, price($amount_to_test, 0, $langs, 1, -1, -1, $conf->currency), price($rule->amount, 0, $langs, 1, -1, -1, $conf->currency));
  1689. }
  1690. // No break, we sould test if another rule is violated
  1691. }
  1692. }
  1693. $this->line->rule_warning_message = implode('\n', $rule_warning_message_tab);
  1694. if ($violation > 0) {
  1695. $tmp = calcul_price_total($this->line->qty, $new_current_total_ttc / $this->line->qty, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller);
  1696. $this->line->value_unit = $tmp[5];
  1697. $this->line->total_ttc = $tmp[2];
  1698. $this->line->total_ht = $tmp[0];
  1699. $this->line->total_tva = $tmp[1];
  1700. $this->line->total_localtax1 = $tmp[9];
  1701. $this->line->total_localtax2 = $tmp[10];
  1702. return false;
  1703. } else {
  1704. return true;
  1705. }
  1706. }
  1707. /**
  1708. * Method to apply the offset if needed
  1709. *
  1710. * @param int $type Type of line
  1711. * @param string $seller Seller, but actually he is unknown
  1712. * @return boolean True=applied, False=not applied
  1713. */
  1714. public function applyOffset($type = 0, $seller = '')
  1715. {
  1716. global $conf, $mysoc;
  1717. if (empty($conf->global->MAIN_USE_EXPENSE_IK)) {
  1718. return false;
  1719. }
  1720. $userauthor = new User($this->db);
  1721. if ($userauthor->fetch($this->fk_user_author) <= 0) {
  1722. $this->error = 'ErrorCantFetchUser';
  1723. $this->errors[] = 'ErrorCantFetchUser';
  1724. return false;
  1725. }
  1726. // We don't know seller and buyer for expense reports
  1727. if (!is_object($seller)) {
  1728. $seller = $mysoc; // We use same than current company (expense report are often done in same country)
  1729. $seller->tva_assuj = 1; // Most seller uses vat
  1730. }
  1731. $expenseik = new ExpenseReportIk($this->db);
  1732. $range = $expenseik->getRangeByUser($userauthor, $this->line->fk_c_exp_tax_cat);
  1733. if (empty($range)) {
  1734. $this->error = 'ErrorNoRangeAvailable';
  1735. $this->errors[] = 'ErrorNoRangeAvailable';
  1736. return false;
  1737. }
  1738. if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) {
  1739. $ikoffset = $range->ikoffset;
  1740. } else {
  1741. $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year
  1742. }
  1743. // Test if ikoffset has been applied for the current month
  1744. if (!$this->offsetAlreadyGiven()) {
  1745. $new_up = $range->coef + ($ikoffset / $this->line->qty);
  1746. $tmp = calcul_price_total($this->line->qty, $new_up, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller);
  1747. $this->line->value_unit = $tmp[5];
  1748. $this->line->total_ttc = $tmp[2];
  1749. $this->line->total_ht = $tmp[0];
  1750. $this->line->total_tva = $tmp[1];
  1751. $this->line->total_localtax1 = $tmp[9];
  1752. $this->line->total_localtax2 = $tmp[10];
  1753. return true;
  1754. }
  1755. return false;
  1756. }
  1757. /**
  1758. * If the sql find any rows then the ikoffset is already given (ikoffset is applied at the first expense report line)
  1759. *
  1760. * @return bool
  1761. */
  1762. public function offsetAlreadyGiven()
  1763. {
  1764. $sql = 'SELECT e.rowid FROM '.MAIN_DB_PREFIX.'expensereport e';
  1765. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."expensereport_det d ON (e.rowid = d.fk_expensereport)";
  1766. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_type_fees f ON (d.fk_c_type_fees = f.id AND f.code = 'EX_KME')";
  1767. $sql .= " WHERE e.fk_user_author = ".(int) $this->fk_user_author;
  1768. $sql .= " AND YEAR(d.date) = '".dol_print_date($this->line->date, '%Y')."' AND MONTH(d.date) = '".dol_print_date($this->line->date, '%m')."'";
  1769. if (!empty($this->line->id)) {
  1770. $sql .= ' AND d.rowid <> '.((int) $this->line->id);
  1771. }
  1772. dol_syslog(get_class($this)."::offsetAlreadyGiven");
  1773. $resql = $this->db->query($sql);
  1774. if ($resql) {
  1775. $num = $this->db->num_rows($resql);
  1776. if ($num > 0) {
  1777. return true;
  1778. }
  1779. } else {
  1780. dol_print_error($this->db);
  1781. }
  1782. return false;
  1783. }
  1784. /**
  1785. * Update an expense report line.
  1786. *
  1787. * @param int $rowid Line to edit
  1788. * @param int $type_fees_id Type payment
  1789. * @param int $projet_id Project id
  1790. * @param double $vatrate Vat rate. Can be '8.5' or '8.5* (8.5NPROM...)'
  1791. * @param string $comments Description
  1792. * @param float $qty Qty
  1793. * @param double $value_unit Unit price (with taxes)
  1794. * @param int $date Date
  1795. * @param int $expensereport_id Expense report id
  1796. * @param int $fk_c_exp_tax_cat Id of category of car
  1797. * @param int $fk_ecm_files Id of ECM file to link to this expensereport line
  1798. * @param int $notrigger 1=No trigger
  1799. * @return int <0 if KO, >0 if OK
  1800. */
  1801. public function updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $expensereport_id, $fk_c_exp_tax_cat = 0, $fk_ecm_files = 0, $notrigger = 0)
  1802. {
  1803. global $user, $mysoc;
  1804. if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) {
  1805. $this->db->begin();
  1806. $error = 0;
  1807. $type = 0; // TODO What if type is service ?
  1808. // We don't know seller and buyer for expense reports
  1809. $seller = $mysoc; // We use same than current company (expense report are often done in same country)
  1810. $seller->tva_assuj = 1; // Most seller uses vat
  1811. $seller->localtax1_assuj = $mysoc->localtax1_assuj; // We don't know, we reuse the state of company
  1812. $seller->localtax2_assuj = $mysoc->localtax1_assuj; // We don't know, we reuse the state of company
  1813. $buyer = new Societe($this->db);
  1814. $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
  1815. // Clean vat code
  1816. $reg = array();
  1817. $vat_src_code = '';
  1818. if (preg_match('/\((.*)\)/', $vatrate, $reg)) {
  1819. $vat_src_code = $reg[1];
  1820. $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
  1821. }
  1822. $vatrate = preg_replace('/\*/', '', $vatrate);
  1823. $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, -1, -1, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
  1824. //var_dump($vatrate);var_dump($localtaxes_type);var_dump($tmp);exit;
  1825. // calcul total of line
  1826. //$total_ttc = price2num($qty*$value_unit, 'MT');
  1827. $tx_tva = $vatrate / 100;
  1828. $tx_tva = $tx_tva + 1;
  1829. $this->line = new ExpenseReportLine($this->db);
  1830. $this->line->comments = $comments;
  1831. $this->line->qty = $qty;
  1832. $this->line->value_unit = $value_unit;
  1833. $this->line->date = $date;
  1834. $this->line->fk_expensereport = $expensereport_id;
  1835. $this->line->fk_c_type_fees = $type_fees_id;
  1836. $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
  1837. $this->line->fk_projet = $projet_id; // deprecated
  1838. $this->line->fk_project = $projet_id;
  1839. $this->line->vat_src_code = $vat_src_code;
  1840. $this->line->vatrate = price2num($vatrate);
  1841. $this->line->localtax1_tx = $localtaxes_type[1];
  1842. $this->line->localtax2_tx = $localtaxes_type[3];
  1843. $this->line->localtax1_type = $localtaxes_type[0];
  1844. $this->line->localtax2_type = $localtaxes_type[2];
  1845. $this->line->total_ttc = $tmp[2];
  1846. $this->line->total_ht = $tmp[0];
  1847. $this->line->total_tva = $tmp[1];
  1848. $this->line->total_localtax1 = $tmp[9];
  1849. $this->line->total_localtax2 = $tmp[10];
  1850. $this->line->fk_ecm_files = $fk_ecm_files;
  1851. $this->line->id = ((int) $rowid);
  1852. // Select des infos sur le type fees
  1853. $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees";
  1854. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  1855. $sql .= " WHERE c.id = ".((int) $type_fees_id);
  1856. $resql = $this->db->query($sql);
  1857. if ($resql) {
  1858. $objp_fees = $this->db->fetch_object($resql);
  1859. $this->line->type_fees_code = $objp_fees->code_type_fees;
  1860. $this->line->type_fees_libelle = $objp_fees->libelle_type_fees;
  1861. $this->db->free($resql);
  1862. }
  1863. // Select des informations du projet
  1864. $sql = "SELECT p.ref as ref_projet, p.title as title_projet";
  1865. $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
  1866. $sql .= " WHERE p.rowid = ".((int) $projet_id);
  1867. $resql = $this->db->query($sql);
  1868. if ($resql) {
  1869. $objp_projet = $this->db->fetch_object($resql);
  1870. $this->line->projet_ref = $objp_projet->ref_projet;
  1871. $this->line->projet_title = $objp_projet->title_projet;
  1872. $this->db->free($resql);
  1873. }
  1874. $this->applyOffset();
  1875. $this->checkRules();
  1876. $result = $this->line->update($user);
  1877. if ($result < 0) {
  1878. $error++;
  1879. }
  1880. if (!$error && !$notrigger) {
  1881. // Call triggers
  1882. $result = $this->call_trigger('EXPENSE_REPORT_DET_MODIFY', $user);
  1883. if ($result < 0) {
  1884. $error++;
  1885. }
  1886. // End call triggers
  1887. }
  1888. if (!$error) {
  1889. $this->db->commit();
  1890. return 1;
  1891. } else {
  1892. $this->error = $this->line->error;
  1893. $this->errors = $this->line->errors;
  1894. $this->db->rollback();
  1895. return -2;
  1896. }
  1897. }
  1898. }
  1899. /**
  1900. * deleteline
  1901. *
  1902. * @param int $rowid Row id
  1903. * @param User $fuser User
  1904. * @param int $notrigger 1=No trigger
  1905. * @return int <0 if KO, >0 if OK
  1906. */
  1907. public function deleteline($rowid, $fuser = '', $notrigger = 0)
  1908. {
  1909. $error=0;
  1910. $this->db->begin();
  1911. if (!$notrigger) {
  1912. // Call triggers
  1913. $result = $this->call_trigger('EXPENSE_REPORT_DET_DELETE', $fuser);
  1914. if ($result < 0) {
  1915. $error++;
  1916. }
  1917. // End call triggers
  1918. }
  1919. $sql = ' DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1920. $sql .= ' WHERE rowid = '.((int) $rowid);
  1921. dol_syslog(get_class($this)."::deleteline sql=".$sql);
  1922. $result = $this->db->query($sql);
  1923. if (!$result || $error > 0 ) {
  1924. $this->error = $this->db->error();
  1925. dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR);
  1926. $this->db->rollback();
  1927. return -1;
  1928. }
  1929. $this->update_price(1);
  1930. $this->db->commit();
  1931. return 1;
  1932. }
  1933. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1934. /**
  1935. * periode_existe
  1936. *
  1937. * @param User $fuser User
  1938. * @param integer $date_debut Start date
  1939. * @param integer $date_fin End date
  1940. * @return int <0 if KO, >0 if OK
  1941. */
  1942. public function periode_existe($fuser, $date_debut, $date_fin)
  1943. {
  1944. // phpcs:enable
  1945. $sql = "SELECT rowid, date_debut, date_fin";
  1946. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  1947. $sql .= " WHERE fk_user_author = '{$fuser->id}'";
  1948. dol_syslog(get_class($this)."::periode_existe sql=".$sql);
  1949. $result = $this->db->query($sql);
  1950. if ($result) {
  1951. $num_rows = $this->db->num_rows($result); $i = 0;
  1952. if ($num_rows > 0) {
  1953. $date_d_form = $date_debut;
  1954. $date_f_form = $date_fin;
  1955. while ($i < $num_rows) {
  1956. $objp = $this->db->fetch_object($result);
  1957. $date_d_req = $this->db->jdate($objp->date_debut); // 3
  1958. $date_f_req = $this->db->jdate($objp->date_fin); // 4
  1959. if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) {
  1960. return $objp->rowid;
  1961. }
  1962. $i++;
  1963. }
  1964. return 0;
  1965. } else {
  1966. return 0;
  1967. }
  1968. } else {
  1969. $this->error = $this->db->lasterror();
  1970. dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR);
  1971. return -1;
  1972. }
  1973. }
  1974. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1975. /**
  1976. * Return list of people with permission to validate expense reports.
  1977. * Search for permission "approve expense report"
  1978. *
  1979. * @return array Array of user ids
  1980. */
  1981. public function fetch_users_approver_expensereport()
  1982. {
  1983. // phpcs:enable
  1984. $users_validator = array();
  1985. $sql = "SELECT DISTINCT ur.fk_user";
  1986. $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
  1987. $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
  1988. $sql .= " UNION";
  1989. $sql .= " SELECT DISTINCT ugu.fk_user";
  1990. $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
  1991. $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
  1992. //print $sql;
  1993. dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql);
  1994. $result = $this->db->query($sql);
  1995. if ($result) {
  1996. $num_rows = $this->db->num_rows($result); $i = 0;
  1997. while ($i < $num_rows) {
  1998. $objp = $this->db->fetch_object($result);
  1999. array_push($users_validator, $objp->fk_user);
  2000. $i++;
  2001. }
  2002. return $users_validator;
  2003. } else {
  2004. $this->error = $this->db->lasterror();
  2005. dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR);
  2006. return -1;
  2007. }
  2008. }
  2009. /**
  2010. * Create a document onto disk accordign to template module.
  2011. *
  2012. * @param string $modele Force le mnodele a utiliser ('' to not force)
  2013. * @param Translate $outputlangs objet lang a utiliser pour traduction
  2014. * @param int $hidedetails Hide details of lines
  2015. * @param int $hidedesc Hide description
  2016. * @param int $hideref Hide ref
  2017. * @param null|array $moreparams Array to provide more information
  2018. * @return int 0 if KO, 1 if OK
  2019. */
  2020. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  2021. {
  2022. global $conf;
  2023. $outputlangs->load("trips");
  2024. if (!dol_strlen($modele)) {
  2025. if (!empty($this->model_pdf)) {
  2026. $modele = $this->model_pdf;
  2027. } elseif (!empty($this->modelpdf)) { // deprecated
  2028. $modele = $this->modelpdf;
  2029. } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) {
  2030. $modele = $conf->global->EXPENSEREPORT_ADDON_PDF;
  2031. }
  2032. }
  2033. if (!empty($modele)) {
  2034. $modelpath = "core/modules/expensereport/doc/";
  2035. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  2036. } else {
  2037. return 0;
  2038. }
  2039. }
  2040. /**
  2041. * List of types
  2042. *
  2043. * @param int $active Active or not
  2044. * @return array
  2045. */
  2046. public function listOfTypes($active = 1)
  2047. {
  2048. global $langs;
  2049. $ret = array();
  2050. $sql = "SELECT id, code, label";
  2051. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees";
  2052. $sql .= " WHERE active = ".((int) $active);
  2053. dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG);
  2054. $result = $this->db->query($sql);
  2055. if ($result) {
  2056. $num = $this->db->num_rows($result);
  2057. $i = 0;
  2058. while ($i < $num) {
  2059. $obj = $this->db->fetch_object($result);
  2060. $ret[$obj->code] = (($langs->transnoentitiesnoconv($obj->code) != $obj->code) ? $langs->transnoentitiesnoconv($obj->code) : $obj->label);
  2061. $i++;
  2062. }
  2063. } else {
  2064. dol_print_error($this->db);
  2065. }
  2066. return $ret;
  2067. }
  2068. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2069. /**
  2070. * Charge indicateurs this->nb pour le tableau de bord
  2071. *
  2072. * @return int <0 if KO, >0 if OK
  2073. */
  2074. public function load_state_board()
  2075. {
  2076. // phpcs:enable
  2077. global $conf, $user;
  2078. $this->nb = array();
  2079. $sql = "SELECT count(ex.rowid) as nb";
  2080. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
  2081. $sql .= " WHERE ex.fk_statut > 0";
  2082. $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
  2083. if (empty($user->rights->expensereport->readall)) {
  2084. $userchildids = $user->getAllChildIds(1);
  2085. $sql .= " AND (ex.fk_user_author IN (".$this->db->sanitize(join(',', $userchildids)).")";
  2086. $sql .= " OR ex.fk_user_validator IN (".$this->db->sanitize(join(',', $userchildids))."))";
  2087. }
  2088. $resql = $this->db->query($sql);
  2089. if ($resql) {
  2090. while ($obj = $this->db->fetch_object($resql)) {
  2091. $this->nb["expensereports"] = $obj->nb;
  2092. }
  2093. $this->db->free($resql);
  2094. return 1;
  2095. } else {
  2096. dol_print_error($this->db);
  2097. $this->error = $this->db->error();
  2098. return -1;
  2099. }
  2100. }
  2101. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2102. /**
  2103. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  2104. *
  2105. * @param User $user Objet user
  2106. * @param string $option 'topay' or 'toapprove'
  2107. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  2108. */
  2109. public function load_board($user, $option = 'topay')
  2110. {
  2111. // phpcs:enable
  2112. global $conf, $langs;
  2113. if ($user->socid) {
  2114. return -1; // protection pour eviter appel par utilisateur externe
  2115. }
  2116. $now = dol_now();
  2117. $sql = "SELECT ex.rowid, ex.date_valid";
  2118. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
  2119. if ($option == 'toapprove') {
  2120. $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED;
  2121. } else {
  2122. $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED;
  2123. }
  2124. $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
  2125. if (empty($user->rights->expensereport->readall)) {
  2126. $userchildids = $user->getAllChildIds(1);
  2127. $sql .= " AND (ex.fk_user_author IN (".$this->db->sanitize(join(',', $userchildids)).")";
  2128. $sql .= " OR ex.fk_user_validator IN (".$this->db->sanitize(join(',', $userchildids))."))";
  2129. }
  2130. $resql = $this->db->query($sql);
  2131. if ($resql) {
  2132. $langs->load("trips");
  2133. $response = new WorkboardResponse();
  2134. if ($option == 'toapprove') {
  2135. $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24;
  2136. $response->label = $langs->trans("ExpenseReportsToApprove");
  2137. $response->labelShort = $langs->trans("ToApprove");
  2138. $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&amp;statut='.self::STATUS_VALIDATED;
  2139. } else {
  2140. $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24;
  2141. $response->label = $langs->trans("ExpenseReportsToPay");
  2142. $response->labelShort = $langs->trans("StatusToPay");
  2143. $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&amp;statut='.self::STATUS_APPROVED;
  2144. }
  2145. $response->img = img_object('', "trip");
  2146. while ($obj = $this->db->fetch_object($resql)) {
  2147. $response->nbtodo++;
  2148. if ($option == 'toapprove') {
  2149. if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) {
  2150. $response->nbtodolate++;
  2151. }
  2152. } else {
  2153. if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) {
  2154. $response->nbtodolate++;
  2155. }
  2156. }
  2157. }
  2158. return $response;
  2159. } else {
  2160. dol_print_error($this->db);
  2161. $this->error = $this->db->error();
  2162. return -1;
  2163. }
  2164. }
  2165. /**
  2166. * Return if an expense report is late or not
  2167. *
  2168. * @param string $option 'topay' or 'toapprove'
  2169. * @return boolean True if late, False if not late
  2170. */
  2171. public function hasDelay($option)
  2172. {
  2173. global $conf;
  2174. // Only valid expenses reports
  2175. if ($option == 'toapprove' && $this->status != 2) {
  2176. return false;
  2177. }
  2178. if ($option == 'topay' && $this->status != 5) {
  2179. return false;
  2180. }
  2181. $now = dol_now();
  2182. if ($option == 'toapprove') {
  2183. return (!empty($this->datevalid) ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay);
  2184. } else {
  2185. return (!empty($this->datevalid) ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay);
  2186. }
  2187. }
  2188. /**
  2189. * Return if object was dispatched into bookkeeping
  2190. *
  2191. * @return int <0 if KO, 0=no, 1=yes
  2192. */
  2193. public function getVentilExportCompta()
  2194. {
  2195. $alreadydispatched = 0;
  2196. $type = 'expense_report';
  2197. $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$this->db->escape($type)."' AND ab.fk_doc = ".((int) $this->id);
  2198. $resql = $this->db->query($sql);
  2199. if ($resql) {
  2200. $obj = $this->db->fetch_object($resql);
  2201. if ($obj) {
  2202. $alreadydispatched = $obj->nb;
  2203. }
  2204. } else {
  2205. $this->error = $this->db->lasterror();
  2206. return -1;
  2207. }
  2208. if ($alreadydispatched) {
  2209. return 1;
  2210. }
  2211. return 0;
  2212. }
  2213. /**
  2214. * Return amount of payments already done
  2215. *
  2216. * @return int Amount of payment already done, <0 if KO
  2217. */
  2218. public function getSumPayments()
  2219. {
  2220. $table = 'payment_expensereport';
  2221. $field = 'fk_expensereport';
  2222. $sql = 'SELECT sum(amount) as amount';
  2223. $sql .= ' FROM '.MAIN_DB_PREFIX.$table;
  2224. $sql .= " WHERE ".$field." = ".((int) $this->id);
  2225. dol_syslog(get_class($this)."::getSumPayments", LOG_DEBUG);
  2226. $resql = $this->db->query($sql);
  2227. if ($resql) {
  2228. $obj = $this->db->fetch_object($resql);
  2229. $this->db->free($resql);
  2230. return (empty($obj->amount) ? 0 : $obj->amount);
  2231. } else {
  2232. $this->error = $this->db->lasterror();
  2233. return -1;
  2234. }
  2235. }
  2236. /**
  2237. * \brief Compute the cost of the kilometers expense based on the number of kilometers and the vehicule category
  2238. *
  2239. * @param int $fk_cat Category of the vehicule used
  2240. * @param real $qty Number of kilometers
  2241. * @param real $tva VAT rate
  2242. * @return int <0 if KO, total ttc if OK
  2243. */
  2244. public function computeTotalKm($fk_cat, $qty, $tva)
  2245. {
  2246. global $langs,$user,$db,$conf;
  2247. $cumulYearQty = 0;
  2248. $ranges = array();
  2249. $coef = 0;
  2250. if ($fk_cat < 0) {
  2251. $this->error = $langs->trans('ErrorBadParameterCat');
  2252. return -1;
  2253. }
  2254. if ($qty <= 0) {
  2255. $this->error = $langs->trans('ErrorBadParameterQty');
  2256. return -1;
  2257. }
  2258. $currentUser = new User($db);
  2259. $currentUser->fetch($this->fk_user);
  2260. $currentUser->getrights('expensereport');
  2261. //Clean
  2262. $qty = price2num($qty);
  2263. $sql = " SELECT r.range_ik, t.ikoffset as offset, t.coef";
  2264. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_ik t";
  2265. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_exp_tax_range r ON r.rowid = t.fk_range";
  2266. $sql .= " WHERE t.fk_c_exp_tax_cat = ".(int) $fk_cat;
  2267. $sql .= " ORDER BY r.range_ik ASC";
  2268. dol_syslog("expenseReport::computeTotalkm sql=".$sql, LOG_DEBUG);
  2269. $result = $this->db->query($sql);
  2270. if ($result) {
  2271. if ($conf->global->EXPENSEREPORT_CALCULATE_MILEAGE_EXPENSE_COEFFICIENT_ON_CURRENT_YEAR) {
  2272. $arrayDate = dol_getdate(dol_now());
  2273. $sql = " SELECT count(n.qty) as cumul FROM ".MAIN_DB_PREFIX."expensereport_det n";
  2274. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expensereport e ON e.rowid = n.fk_expensereport";
  2275. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_fees tf ON tf.id = n.fk_c_type_fees";
  2276. $sql.= " WHERE e.fk_user_author = ".(int) $this->fk_user_author;
  2277. $sql.= " AND YEAR(n.date) = ".(int) $arrayDate['year'];
  2278. $sql.= " AND tf.code = 'EX_KME' ";
  2279. $sql.= " AND e.fk_statut = ".(int) ExpenseReport::STATUS_VALIDATED;
  2280. $resql = $this->db->query($sql);
  2281. if ($resql) {
  2282. $obj = $this->db->fetch_object($resql);
  2283. $cumulYearQty = $obj->cumul;
  2284. }
  2285. $qty = $cumulYearQty + $qty;
  2286. }
  2287. $num = $this->db->num_rows($result);
  2288. if ($num) {
  2289. for ($i = 0; $i < $num; $i++) {
  2290. $obj = $this->db->fetch_object($result);
  2291. $ranges[$i] = $obj;
  2292. }
  2293. for ($i = 0; $i < $num; $i++) {
  2294. if ($i < ($num - 1)) {
  2295. if ($qty > $ranges[$i]->range_ik && $qty < $ranges[$i+1]->range_ik) {
  2296. $coef = $ranges[$i]->coef;
  2297. $offset = $ranges[$i]->offset;
  2298. }
  2299. } else {
  2300. if ($qty > $ranges[$i]->range_ik) {
  2301. $coef = $ranges[$i]->coef;
  2302. $offset = $ranges[$i]->offset;
  2303. }
  2304. }
  2305. }
  2306. $total_ht = $coef;
  2307. return $total_ht;
  2308. } else {
  2309. $this->error = $langs->trans('TaxUndefinedForThisCategory');
  2310. return 0;
  2311. }
  2312. } else {
  2313. $this->error = $this->db->error()." sql=".$sql;
  2314. return -1;
  2315. }
  2316. }
  2317. }
  2318. /**
  2319. * Class of expense report details lines
  2320. */
  2321. class ExpenseReportLine extends CommonObjectLine
  2322. {
  2323. /**
  2324. * @var DoliDB Database handler.
  2325. */
  2326. public $db;
  2327. /**
  2328. * @var string Name of table without prefix where object is stored
  2329. */
  2330. public $table_element = 'expensereport_det';
  2331. /**
  2332. * @var string Error code (or message)
  2333. */
  2334. public $error = '';
  2335. /**
  2336. * @var int ID
  2337. */
  2338. public $rowid;
  2339. public $comments;
  2340. public $qty;
  2341. public $value_unit;
  2342. public $date;
  2343. /**
  2344. * @var int ID
  2345. */
  2346. public $fk_c_type_fees;
  2347. /**
  2348. * @var int ID
  2349. */
  2350. public $fk_c_exp_tax_cat;
  2351. /**
  2352. * @var int ID
  2353. */
  2354. public $fk_projet;
  2355. /**
  2356. * @var int ID
  2357. */
  2358. public $fk_expensereport;
  2359. public $type_fees_code;
  2360. public $type_fees_libelle;
  2361. public $type_fees_accountancy_code;
  2362. public $projet_ref;
  2363. public $projet_title;
  2364. public $rang;
  2365. public $vatrate;
  2366. public $vat_src_code;
  2367. public $tva_tx;
  2368. public $localtax1_tx;
  2369. public $localtax2_tx;
  2370. public $localtax1_type;
  2371. public $localtax2_type;
  2372. public $total_ht;
  2373. public $total_tva;
  2374. public $total_ttc;
  2375. public $total_localtax1;
  2376. public $total_localtax2;
  2377. // Multicurrency
  2378. /**
  2379. * @var int Currency ID
  2380. */
  2381. public $fk_multicurrency;
  2382. /**
  2383. * @var string multicurrency code
  2384. */
  2385. public $multicurrency_code;
  2386. public $multicurrency_tx;
  2387. public $multicurrency_total_ht;
  2388. public $multicurrency_total_tva;
  2389. public $multicurrency_total_ttc;
  2390. /**
  2391. * @var int ID into llx_ecm_files table to link line to attached file
  2392. */
  2393. public $fk_ecm_files;
  2394. public $rule_warning_message;
  2395. /**
  2396. * Constructor
  2397. *
  2398. * @param DoliDB $db Handlet database
  2399. */
  2400. public function __construct($db)
  2401. {
  2402. $this->db = $db;
  2403. }
  2404. /**
  2405. * Fetch record for expense report detailed line
  2406. *
  2407. * @param int $rowid Id of object to load
  2408. * @return int <0 if KO, >0 if OK
  2409. */
  2410. public function fetch($rowid)
  2411. {
  2412. $sql = 'SELECT fde.rowid, fde.fk_expensereport, fde.fk_c_type_fees, fde.fk_c_exp_tax_cat, fde.fk_projet as fk_project, fde.date,';
  2413. $sql .= ' fde.tva_tx as vatrate, fde.vat_src_code, fde.comments, fde.qty, fde.value_unit, fde.total_ht, fde.total_tva, fde.total_ttc, fde.fk_ecm_files,';
  2414. $sql .= ' fde.localtax1_tx, fde.localtax2_tx, fde.localtax1_type, fde.localtax2_type, fde.total_localtax1, fde.total_localtax2, fde.rule_warning_message,';
  2415. $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,';
  2416. $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref';
  2417. $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde';
  2418. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON fde.fk_c_type_fees=ctf.id'; // Sometimes type of expense report has been removed, so we use a left join here.
  2419. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid';
  2420. $sql .= ' WHERE fde.rowid = '.((int) $rowid);
  2421. $result = $this->db->query($sql);
  2422. if ($result) {
  2423. $objp = $this->db->fetch_object($result);
  2424. $this->rowid = $objp->rowid;
  2425. $this->id = $objp->rowid;
  2426. $this->ref = $objp->ref;
  2427. $this->fk_expensereport = $objp->fk_expensereport;
  2428. $this->comments = $objp->comments;
  2429. $this->qty = $objp->qty;
  2430. $this->date = $objp->date;
  2431. $this->dates = $this->db->jdate($objp->date);
  2432. $this->value_unit = $objp->value_unit;
  2433. $this->fk_c_type_fees = $objp->fk_c_type_fees;
  2434. $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
  2435. $this->fk_projet = $objp->fk_project; // deprecated
  2436. $this->fk_project = $objp->fk_project;
  2437. $this->type_fees_code = $objp->type_fees_code;
  2438. $this->type_fees_libelle = $objp->type_fees_libelle;
  2439. $this->projet_ref = $objp->projet_ref;
  2440. $this->projet_title = $objp->projet_title;
  2441. $this->vatrate = $objp->vatrate;
  2442. $this->vat_src_code = $objp->vat_src_code;
  2443. $this->localtax1_tx = $objp->localtax1_tx;
  2444. $this->localtax2_tx = $objp->localtax2_tx;
  2445. $this->localtax1_type = $objp->localtax1_type;
  2446. $this->localtax2_type = $objp->localtax2_type;
  2447. $this->total_ht = $objp->total_ht;
  2448. $this->total_tva = $objp->total_tva;
  2449. $this->total_ttc = $objp->total_ttc;
  2450. $this->total_localtax1 = $objp->total_localtax1;
  2451. $this->total_localtax2 = $objp->total_localtax2;
  2452. $this->fk_ecm_files = $objp->fk_ecm_files;
  2453. $this->rule_warning_message = $objp->rule_warning_message;
  2454. $this->db->free($result);
  2455. } else {
  2456. dol_print_error($this->db);
  2457. }
  2458. }
  2459. /**
  2460. * Insert a line of expense report
  2461. *
  2462. * @param int $notrigger 1=No trigger
  2463. * @param bool $fromaddline false=keep default behavior, true=exclude the update_price() of parent object
  2464. * @return int <0 if KO, >0 if OK
  2465. */
  2466. public function insert($notrigger = 0, $fromaddline = false)
  2467. {
  2468. global $langs, $user, $conf;
  2469. $error = 0;
  2470. dol_syslog("ExpenseReportLine::Insert", LOG_DEBUG);
  2471. // Clean parameters
  2472. $this->comments = trim($this->comments);
  2473. if (empty($this->value_unit)) {
  2474. $this->value_unit = 0;
  2475. }
  2476. $this->qty = price2num($this->qty);
  2477. $this->vatrate = price2num($this->vatrate);
  2478. if (empty($this->fk_c_exp_tax_cat)) {
  2479. $this->fk_c_exp_tax_cat = 0;
  2480. }
  2481. $this->db->begin();
  2482. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det';
  2483. $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,';
  2484. $sql .= ' tva_tx, vat_src_code,';
  2485. $sql .= ' localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
  2486. $sql .= ' comments, qty, value_unit,';
  2487. $sql .= ' total_ht, total_tva, total_ttc,';
  2488. $sql .= ' total_localtax1, total_localtax2,';
  2489. $sql .= ' date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)';
  2490. $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).",";
  2491. $sql .= " ".((int) $this->fk_c_type_fees).",";
  2492. $sql .= " ".((int) (!empty($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : ((!empty($this->fk_projet) && $this->fk_projet > 0) ? $this->fk_projet : 'null')).",";
  2493. $sql .= " ".((float) $this->vatrate).",";
  2494. $sql .= " '".$this->db->escape(empty($this->vat_src_code) ? '' : $this->vat_src_code)."',";
  2495. $sql .= " ".((float) price2num($this->localtax1_tx)).",";
  2496. $sql .= " ".((float) price2num($this->localtax2_tx)).",";
  2497. $sql .= " '".$this->db->escape($this->localtax1_type)."',";
  2498. $sql .= " '".$this->db->escape($this->localtax2_type)."',";
  2499. $sql .= " '".$this->db->escape($this->comments)."',";
  2500. $sql .= " ".((float) $this->qty).",";
  2501. $sql .= " ".((float) $this->value_unit).",";
  2502. $sql .= " ".((float) price2num($this->total_ht)).",";
  2503. $sql .= " ".((float) price2num($this->total_tva)).",";
  2504. $sql .= " ".((float) price2num($this->total_ttc)).",";
  2505. $sql .= " ".((float) price2num($this->total_localtax1)).",";
  2506. $sql .= " ".((float) price2num($this->total_localtax2)).",";
  2507. $sql .= " '".$this->db->idate($this->date)."',";
  2508. $sql .= " ".(empty($this->rule_warning_message) ? 'null' : "'".$this->db->escape($this->rule_warning_message)."'").",";
  2509. $sql .= " ".((int) $this->fk_c_exp_tax_cat).",";
  2510. $sql .= " ".($this->fk_ecm_files > 0 ? ((int) $this->fk_ecm_files) : 'null');
  2511. $sql .= ")";
  2512. $resql = $this->db->query($sql);
  2513. if ($resql) {
  2514. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det');
  2515. if (!$error && !$notrigger) {
  2516. // Call triggers
  2517. $result = $this->call_trigger('EXPENSE_REPORT_DET_CREATE', $user);
  2518. if ($result < 0) {
  2519. $error++;
  2520. }
  2521. // End call triggers
  2522. }
  2523. if (!$fromaddline) {
  2524. $tmpparent = new ExpenseReport($this->db);
  2525. $tmpparent->fetch($this->fk_expensereport);
  2526. $result = $tmpparent->update_price(1);
  2527. if ($result < 0) {
  2528. $error++;
  2529. $this->error = $tmpparent->error;
  2530. $this->errors = $tmpparent->errors;
  2531. }
  2532. }
  2533. } else {
  2534. $error++;
  2535. }
  2536. if (!$error) {
  2537. $this->db->commit();
  2538. return $this->id;
  2539. } else {
  2540. $this->error = $this->db->lasterror();
  2541. dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR);
  2542. $this->db->rollback();
  2543. return -2;
  2544. }
  2545. }
  2546. /**
  2547. * Function to get total amount in expense reports for a same rule
  2548. *
  2549. * @param ExpenseReportRule $rule object rule to check
  2550. * @param int $fk_user user author id
  2551. * @param string $mode day|EX_DAY / month|EX_MON / year|EX_YEA to get amount
  2552. * @return float Amount
  2553. */
  2554. public function getExpAmount(ExpenseReportRule $rule, $fk_user, $mode = 'day')
  2555. {
  2556. $amount = 0;
  2557. $sql = 'SELECT SUM(d.total_ttc) as total_amount';
  2558. $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det d';
  2559. $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'expensereport e ON (d.fk_expensereport = e.rowid)';
  2560. $sql .= ' WHERE e.fk_user_author = '.((int) $fk_user);
  2561. if (!empty($this->id)) {
  2562. $sql .= ' AND d.rowid <> '.((int) $this->id);
  2563. }
  2564. $sql .= ' AND d.fk_c_type_fees = '.((int) $rule->fk_c_type_fees);
  2565. if ($mode == 'day' || $mode == 'EX_DAY') {
  2566. $sql .= " AND d.date = '".dol_print_date($this->date, '%Y-%m-%d')."'";
  2567. } elseif ($mode == 'mon' || $mode == 'EX_MON') {
  2568. $sql .= " AND DATE_FORMAT(d.date, '%Y-%m') = '".dol_print_date($this->date, '%Y-%m')."'"; // @todo DATE_FORMAT is forbidden
  2569. } elseif ($mode == 'year' || $mode == 'EX_YEA') {
  2570. $sql .= " AND DATE_FORMAT(d.date, '%Y') = '".dol_print_date($this->date, '%Y')."'"; // @todo DATE_FORMAT is forbidden
  2571. }
  2572. dol_syslog('ExpenseReportLine::getExpAmount');
  2573. $resql = $this->db->query($sql);
  2574. if ($resql) {
  2575. $num = $this->db->num_rows($resql);
  2576. if ($num > 0) {
  2577. $obj = $this->db->fetch_object($resql);
  2578. $amount = (double) $obj->total_amount;
  2579. }
  2580. } else {
  2581. dol_print_error($this->db);
  2582. }
  2583. return $amount + $this->total_ttc;
  2584. }
  2585. /**
  2586. * Update line
  2587. *
  2588. * @param User $user User
  2589. * @return int <0 if KO, >0 if OK
  2590. */
  2591. public function update(User $user)
  2592. {
  2593. global $langs, $conf;
  2594. $error = 0;
  2595. // Clean parameters
  2596. $this->comments = trim($this->comments);
  2597. $this->vatrate = price2num($this->vatrate);
  2598. $this->value_unit = price2num($this->value_unit);
  2599. if (empty($this->fk_c_exp_tax_cat)) {
  2600. $this->fk_c_exp_tax_cat = 0;
  2601. }
  2602. $this->db->begin();
  2603. // Update line in database
  2604. $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET";
  2605. $sql .= " comments='".$this->db->escape($this->comments)."'";
  2606. $sql .= ", value_unit = ".((float) $this->value_unit);
  2607. $sql .= ", qty=".((float) $this->qty);
  2608. $sql .= ", date='".$this->db->idate($this->date)."'";
  2609. $sql .= ", total_ht=".((float) price2num($this->total_ht, 'MT'));
  2610. $sql .= ", total_tva=".((float) price2num($this->total_tva, 'MT'));
  2611. $sql .= ", total_ttc=".((float) price2num($this->total_ttc, 'MT'));
  2612. $sql .= ", total_localtax1=".((float) price2num($this->total_localtax1, 'MT'));
  2613. $sql .= ", total_localtax2=".((float) price2num($this->total_localtax2, 'MT'));
  2614. $sql .= ", tva_tx=".((float) $this->vatrate);
  2615. $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'";
  2616. $sql .= ", localtax1_tx=".((float) $this->localtax1_tx);
  2617. $sql .= ", localtax2_tx=".((float) $this->localtax2_tx);
  2618. $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
  2619. $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
  2620. $sql .= ", rule_warning_message='".$this->db->escape($this->rule_warning_message)."'";
  2621. $sql .= ", fk_c_exp_tax_cat=".$this->db->escape($this->fk_c_exp_tax_cat);
  2622. $sql .= ", fk_ecm_files=".($this->fk_ecm_files > 0 ? ((int) $this->fk_ecm_files) : 'null');
  2623. if ($this->fk_c_type_fees) {
  2624. $sql .= ", fk_c_type_fees = ".((int) $this->fk_c_type_fees);
  2625. } else {
  2626. $sql .= ", fk_c_type_fees=null";
  2627. }
  2628. if ($this->fk_project > 0) {
  2629. $sql .= ", fk_projet=".((int) $this->fk_project);
  2630. } else {
  2631. $sql .= ", fk_projet=null";
  2632. }
  2633. $sql .= " WHERE rowid = ".((int) ($this->rowid ? $this->rowid : $this->id));
  2634. dol_syslog("ExpenseReportLine::update");
  2635. $resql = $this->db->query($sql);
  2636. if ($resql) {
  2637. $tmpparent = new ExpenseReport($this->db);
  2638. $result = $tmpparent->fetch($this->fk_expensereport);
  2639. if ($result > 0) {
  2640. $result = $tmpparent->update_price(1);
  2641. if ($result < 0) {
  2642. $error++;
  2643. $this->error = $tmpparent->error;
  2644. $this->errors = $tmpparent->errors;
  2645. }
  2646. } else {
  2647. $error++;
  2648. $this->error = $tmpparent->error;
  2649. $this->errors = $tmpparent->errors;
  2650. }
  2651. } else {
  2652. $error++;
  2653. dol_print_error($this->db);
  2654. }
  2655. if (!$error) {
  2656. $this->db->commit();
  2657. return 1;
  2658. } else {
  2659. $this->error = $this->db->lasterror();
  2660. dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR);
  2661. $this->db->rollback();
  2662. return -2;
  2663. }
  2664. }
  2665. // ajouter ici comput_ ...
  2666. }