expensereport.class.php 95 KB

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