userinvoice.class.php.back 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2023 Szollősi László <szollosi.laszlo@smbinfo.hu>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file class/userinvoice.class.php
  20. * \ingroup financialreport
  21. * \brief This file is a CRUD class file for UserInvoice (Create/Read/Update/Delete)
  22. */
  23. // Put here all includes required by your class file
  24. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  25. //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  26. //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  27. /**
  28. * Class for UserInvoice
  29. */
  30. class UserInvoice extends CommonObject
  31. {
  32. /**
  33. * @var string ID of module.
  34. */
  35. public $module = 'financialreport';
  36. /**
  37. * @var string ID to identify managed object.
  38. */
  39. public $element = 'userinvoice';
  40. /**
  41. * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
  42. */
  43. public $table_element = 'financialreport_userinvoice';
  44. /**
  45. * @var int Does this object support multicompany module ?
  46. * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  47. */
  48. public $ismultientitymanaged = 0;
  49. /**
  50. * @var int Does object support extrafields ? 0=No, 1=Yes
  51. */
  52. public $isextrafieldmanaged = 1;
  53. /**
  54. * @var string String with name of icon for userinvoice. Must be a 'fa-xxx' fontawesome code (or 'fa-xxx_fa_color_size') or 'userinvoice@financialreport' if picto is file 'img/object_userinvoice.png'.
  55. */
  56. public $picto = 'fa-file';
  57. const STATUS_DRAFT = 0;
  58. const STATUS_VALIDATED = 1;
  59. const STATUS_CANCELED = 9;
  60. /**
  61. * 'type' field format:
  62. * 'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',
  63. * 'select' (list of values are in 'options'),
  64. * 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]',
  65. * 'chkbxlst:...',
  66. * 'varchar(x)',
  67. * 'text', 'text:none', 'html',
  68. * 'double(24,8)', 'real', 'price',
  69. * 'date', 'datetime', 'timestamp', 'duration',
  70. * 'boolean', 'checkbox', 'radio', 'array',
  71. * 'mail', 'phone', 'url', 'password', 'ip'
  72. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  73. * 'label' the translation key.
  74. * 'picto' is code of a picto to show before value in forms
  75. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM' or '!empty($conf->multicurrency->enabled)' ...)
  76. * 'position' is the sort order of field.
  77. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  78. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  79. * 'noteditable' says if field is not editable (1 or 0)
  80. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  81. * 'index' if we want an index in database.
  82. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  83. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  84. * 'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage)
  85. * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
  86. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  87. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  88. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  89. * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
  90. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  91. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  92. * 'validate' is 1 if need to validate with $this->validateField()
  93. * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
  94. *
  95. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  96. */
  97. // BEGIN MODULEBUILDER PROPERTIES
  98. /**
  99. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  100. */
  101. public $fields=array(
  102. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
  103. 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'validate'=>'1', 'comment'=>"Reference of object"),
  104. 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'help'=>"Help text", 'showoncombobox'=>'2', 'validate'=>'1',),
  105. 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>3, 'validate'=>'1',),
  106. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
  107. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
  108. 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'picto'=>'user', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
  109. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'picto'=>'user', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
  110. 'user_id' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserId', 'enabled'=>'1', 'position'=>70, 'notnull'=>1, 'visible'=>1, 'noteditable'=>'1',),
  111. 'payment_type' => array('type'=>'integer', 'label'=>'PaymentType', 'enabled'=>'1', 'position'=>71, 'notnull'=>1, 'visible'=>1, 'arrayofkeyval'=>array('0'=>'Prepayment', '1'=>'Withholding', '2'=>'Jutal&eacute;k'),),
  112. 'amount' => array('type'=>'double', 'label'=>'Amount1', 'enabled'=>'1', 'position'=>72, 'notnull'=>1, 'visible'=>1,),
  113. 'currency' => array('type'=>'integer', 'label'=>'Currency', 'enabled'=>'1', 'position'=>73, 'notnull'=>1, 'visible'=>1, 'arrayofkeyval'=>array('0'=>'HUF'),),
  114. 'individual' => array('type'=>'integer', 'label'=>'IndividualFinancial', 'enabled'=>'1', 'position'=>74, 'notnull'=>1, 'visible'=>2, 'arrayofkeyval'=>array('0'=>'No', '1'=>'Yes'),),
  115. 'payed' => array('type'=>'integer', 'label'=>'Payed', 'enabled'=>'1', 'position'=>75, 'notnull'=>1, 'visible'=>1, 'noteditable'=>'1', 'arrayofkeyval'=>array('0'=>'No', '1'=>'Yes'),),
  116. 'paymentdate' => array('type'=>'datetime', 'label'=>'PaymentDate', 'enabled'=>'1', 'position'=>76, 'notnull'=>0, 'visible'=>1, 'noteditable'=>'1',),
  117. 'invoices' => array('type'=>'text', 'label'=>'Invoices', 'enabled'=>'1', 'position'=>77, 'notnull'=>0, 'visible'=>0,),
  118. 'receipt_pdf' => array('type'=>'varchar(255)', 'label'=>'ReceiptPDF', 'enabled'=>'1', 'position'=>78, 'notnull'=>0, 'visible'=>5,),
  119. );
  120. public $rowid;
  121. public $ref;
  122. public $label;
  123. public $description;
  124. public $date_creation;
  125. public $tms;
  126. public $fk_user_creat;
  127. public $fk_user_modif;
  128. public $user_id;
  129. public $payment_type;
  130. public $amount;
  131. public $currency;
  132. public $individual;
  133. public $payed;
  134. public $paymentdate;
  135. public $invoices;
  136. public $receipt_pdf;
  137. // END MODULEBUILDER PROPERTIES
  138. // If this object has a subtable with lines
  139. // /**
  140. // * @var string Name of subtable line
  141. // */
  142. // public $table_element_line = 'financialreport_userinvoiceline';
  143. // /**
  144. // * @var string Field with ID of parent key if this object has a parent
  145. // */
  146. // public $fk_element = 'fk_userinvoice';
  147. // /**
  148. // * @var string Name of subtable class that manage subtable lines
  149. // */
  150. // public $class_element_line = 'UserInvoiceline';
  151. // /**
  152. // * @var array List of child tables. To test if we can delete object.
  153. // */
  154. // protected $childtables = array();
  155. // /**
  156. // * @var array List of child tables. To know object to delete on cascade.
  157. // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
  158. // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
  159. // */
  160. // protected $childtablesoncascade = array('financialreport_userinvoicedet');
  161. // /**
  162. // * @var UserInvoiceLine[] Array of subtable lines
  163. // */
  164. // public $lines = array();
  165. /**
  166. * Constructor
  167. *
  168. * @param DoliDb $db Database handler
  169. */
  170. public function __construct(DoliDB $db)
  171. {
  172. global $conf, $langs;
  173. $this->db = $db;
  174. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
  175. $this->fields['rowid']['visible'] = 0;
  176. }
  177. if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
  178. $this->fields['entity']['enabled'] = 0;
  179. }
  180. // Example to show how to set values of fields definition dynamically
  181. /*if ($user->rights->financialreport->userinvoice->read) {
  182. $this->fields['myfield']['visible'] = 1;
  183. $this->fields['myfield']['noteditable'] = 0;
  184. }*/
  185. // Unset fields that are disabled
  186. foreach ($this->fields as $key => $val) {
  187. if (isset($val['enabled']) && empty($val['enabled'])) {
  188. unset($this->fields[$key]);
  189. }
  190. }
  191. // Translate some data of arrayofkeyval
  192. if (is_object($langs)) {
  193. foreach ($this->fields as $key => $val) {
  194. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  195. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  196. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  197. }
  198. }
  199. }
  200. }
  201. }
  202. /**
  203. * Create object into database
  204. *
  205. * @param User $user User that creates
  206. * @param bool $notrigger false=launch triggers after, true=disable triggers
  207. * @return int <0 if KO, Id of created object if OK
  208. */
  209. public function create(User $user, $notrigger = false)
  210. {
  211. $resultcreate = $this->createCommon($user, $notrigger);
  212. //$resultvalidate = $this->validate($user, $notrigger);
  213. return $resultcreate;
  214. }
  215. /**
  216. * Clone an object into another one
  217. *
  218. * @param User $user User that creates
  219. * @param int $fromid Id of object to clone
  220. * @return mixed New object created, <0 if KO
  221. */
  222. public function createFromClone(User $user, $fromid)
  223. {
  224. global $langs, $extrafields;
  225. $error = 0;
  226. dol_syslog(__METHOD__, LOG_DEBUG);
  227. $object = new self($this->db);
  228. $this->db->begin();
  229. // Load source object
  230. $result = $object->fetchCommon($fromid);
  231. if ($result > 0 && !empty($object->table_element_line)) {
  232. $object->fetchLines();
  233. }
  234. // get lines so they will be clone
  235. //foreach($this->lines as $line)
  236. // $line->fetch_optionals();
  237. // Reset some properties
  238. unset($object->id);
  239. unset($object->fk_user_creat);
  240. unset($object->import_key);
  241. // Clear fields
  242. if (property_exists($object, 'ref')) {
  243. $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
  244. }
  245. if (property_exists($object, 'label')) {
  246. $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  247. }
  248. if (property_exists($object, 'status')) {
  249. $object->status = self::STATUS_DRAFT;
  250. }
  251. if (property_exists($object, 'date_creation')) {
  252. $object->date_creation = dol_now();
  253. }
  254. if (property_exists($object, 'date_modification')) {
  255. $object->date_modification = null;
  256. }
  257. // ...
  258. // Clear extrafields that are unique
  259. if (is_array($object->array_options) && count($object->array_options) > 0) {
  260. $extrafields->fetch_name_optionals_label($this->table_element);
  261. foreach ($object->array_options as $key => $option) {
  262. $shortkey = preg_replace('/options_/', '', $key);
  263. if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
  264. //var_dump($key);
  265. //var_dump($clonedObj->array_options[$key]); exit;
  266. unset($object->array_options[$key]);
  267. }
  268. }
  269. }
  270. // Create clone
  271. $object->context['createfromclone'] = 'createfromclone';
  272. $result = $object->createCommon($user);
  273. if ($result < 0) {
  274. $error++;
  275. $this->error = $object->error;
  276. $this->errors = $object->errors;
  277. }
  278. if (!$error) {
  279. // copy internal contacts
  280. if ($this->copy_linked_contact($object, 'internal') < 0) {
  281. $error++;
  282. }
  283. }
  284. if (!$error) {
  285. // copy external contacts if same company
  286. if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
  287. if ($this->copy_linked_contact($object, 'external') < 0) {
  288. $error++;
  289. }
  290. }
  291. }
  292. unset($object->context['createfromclone']);
  293. // End
  294. if (!$error) {
  295. $this->db->commit();
  296. return $object;
  297. } else {
  298. $this->db->rollback();
  299. return -1;
  300. }
  301. }
  302. /**
  303. * Load object in memory from the database
  304. *
  305. * @param int $id Id object
  306. * @param string $ref Ref
  307. * @return int <0 if KO, 0 if not found, >0 if OK
  308. */
  309. public function fetch($id, $ref = null)
  310. {
  311. $result = $this->fetchCommon($id, $ref);
  312. if ($result > 0 && !empty($this->table_element_line)) {
  313. $this->fetchLines();
  314. }
  315. return $result;
  316. }
  317. /**
  318. * Load object lines in memory from the database
  319. *
  320. * @return int <0 if KO, 0 if not found, >0 if OK
  321. */
  322. public function fetchLines()
  323. {
  324. $this->lines = array();
  325. $result = $this->fetchLinesCommon();
  326. return $result;
  327. }
  328. /**
  329. * Load list of objects in memory from the database.
  330. *
  331. * @param string $sortorder Sort Order
  332. * @param string $sortfield Sort field
  333. * @param int $limit limit
  334. * @param int $offset Offset
  335. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  336. * @param string $filtermode Filter mode (AND or OR)
  337. * @return array|int int <0 if KO, array of pages if OK
  338. */
  339. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  340. {
  341. global $conf;
  342. dol_syslog(__METHOD__, LOG_DEBUG);
  343. $records = array();
  344. $sql = "SELECT ";
  345. $sql .= $this->getFieldList('t');
  346. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
  347. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  348. $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
  349. } else {
  350. $sql .= " WHERE 1 = 1";
  351. }
  352. // Manage filter
  353. $sqlwhere = array();
  354. if (count($filter) > 0) {
  355. foreach ($filter as $key => $value) {
  356. if ($key == 't.rowid') {
  357. $sqlwhere[] = $key." = ".((int) $value);
  358. } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
  359. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  360. } elseif ($key == 'customsql') {
  361. $sqlwhere[] = $value;
  362. } elseif (strpos($value, '%') === false) {
  363. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  364. } else {
  365. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  366. }
  367. }
  368. }
  369. if (count($sqlwhere) > 0) {
  370. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  371. }
  372. if (!empty($sortfield)) {
  373. $sql .= $this->db->order($sortfield, $sortorder);
  374. }
  375. if (!empty($limit)) {
  376. $sql .= $this->db->plimit($limit, $offset);
  377. }
  378. $resql = $this->db->query($sql);
  379. if ($resql) {
  380. $num = $this->db->num_rows($resql);
  381. $i = 0;
  382. while ($i < ($limit ? min($limit, $num) : $num)) {
  383. $obj = $this->db->fetch_object($resql);
  384. $record = new self($this->db);
  385. $record->setVarsFromFetchObj($obj);
  386. $records[$record->id] = $record;
  387. $i++;
  388. }
  389. $this->db->free($resql);
  390. return $records;
  391. } else {
  392. $this->errors[] = 'Error '.$this->db->lasterror();
  393. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  394. return -1;
  395. }
  396. }
  397. /**
  398. * Update object into database
  399. *
  400. * @param User $user User that modifies
  401. * @param bool $notrigger false=launch triggers after, true=disable triggers
  402. * @return int <0 if KO, >0 if OK
  403. */
  404. public function update(User $user, $notrigger = false)
  405. {
  406. return $this->updateCommon($user, $notrigger);
  407. }
  408. /**
  409. * Delete object in database
  410. *
  411. * @param User $user User that deletes
  412. * @param bool $notrigger false=launch triggers after, true=disable triggers
  413. * @return int <0 if KO, >0 if OK
  414. */
  415. public function delete(User $user, $notrigger = false)
  416. {
  417. return $this->deleteCommon($user, $notrigger);
  418. //return $this->deleteCommon($user, $notrigger, 1);
  419. }
  420. /**
  421. * Delete a line of object in database
  422. *
  423. * @param User $user User that delete
  424. * @param int $idline Id of line to delete
  425. * @param bool $notrigger false=launch triggers after, true=disable triggers
  426. * @return int >0 if OK, <0 if KO
  427. */
  428. public function deleteLine(User $user, $idline, $notrigger = false)
  429. {
  430. if ($this->status < 0) {
  431. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  432. return -2;
  433. }
  434. return $this->deleteLineCommon($user, $idline, $notrigger);
  435. }
  436. /**
  437. * Validate object
  438. *
  439. * @param User $user User making status change
  440. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  441. * @return int <=0 if OK, 0=Nothing done, >0 if KO
  442. */
  443. public function validate($user, $notrigger = 0)
  444. {
  445. global $conf, $langs;
  446. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  447. $error = 0;
  448. // Protection
  449. if ($this->status == self::STATUS_VALIDATED) {
  450. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  451. return 0;
  452. }
  453. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->financialreport->userinvoice->write))
  454. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->financialreport->userinvoice->userinvoice_advance->validate))))
  455. {
  456. $this->error='NotEnoughPermissions';
  457. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  458. return -1;
  459. }*/
  460. $now = dol_now();
  461. $this->db->begin();
  462. // Define new ref
  463. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  464. $num = $this->getNextNumRef();
  465. } else {
  466. $num = $this->ref;
  467. }
  468. $this->newref = $num;
  469. if (!empty($num)) {
  470. // Validate
  471. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  472. $sql .= " SET ref = '".$this->db->escape($num)."',";
  473. $sql .= " status = ".self::STATUS_VALIDATED;
  474. if (!empty($this->fields['date_validation'])) {
  475. $sql .= ", date_validation = '".$this->db->idate($now)."'";
  476. }
  477. if (!empty($this->fields['fk_user_valid'])) {
  478. $sql .= ", fk_user_valid = ".((int) $user->id);
  479. }
  480. $sql .= " WHERE rowid = ".((int) $this->id);
  481. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  482. $resql = $this->db->query($sql);
  483. if (!$resql) {
  484. dol_print_error($this->db);
  485. $this->error = $this->db->lasterror();
  486. $error++;
  487. }
  488. if (!$error && !$notrigger) {
  489. // Call trigger
  490. $result = $this->call_trigger('USERINVOICE_VALIDATE', $user);
  491. if ($result < 0) {
  492. $error++;
  493. }
  494. // End call triggers
  495. }
  496. }
  497. if (!$error) {
  498. $this->oldref = $this->ref;
  499. // Rename directory if dir was a temporary ref
  500. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  501. // Now we rename also files into index
  502. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'userinvoice/".$this->db->escape($this->newref)."'";
  503. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'userinvoice/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  504. $resql = $this->db->query($sql);
  505. if (!$resql) {
  506. $error++; $this->error = $this->db->lasterror();
  507. }
  508. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  509. $oldref = dol_sanitizeFileName($this->ref);
  510. $newref = dol_sanitizeFileName($num);
  511. $dirsource = $conf->financialreport->dir_output.'/userinvoice/'.$oldref;
  512. $dirdest = $conf->financialreport->dir_output.'/userinvoice/'.$newref;
  513. if (!$error && file_exists($dirsource)) {
  514. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  515. if (@rename($dirsource, $dirdest)) {
  516. dol_syslog("Rename ok");
  517. // Rename docs starting with $oldref with $newref
  518. $listoffiles = dol_dir_list($conf->financialreport->dir_output.'/userinvoice/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  519. foreach ($listoffiles as $fileentry) {
  520. $dirsource = $fileentry['name'];
  521. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  522. $dirsource = $fileentry['path'].'/'.$dirsource;
  523. $dirdest = $fileentry['path'].'/'.$dirdest;
  524. @rename($dirsource, $dirdest);
  525. }
  526. }
  527. }
  528. }
  529. }
  530. // Set new ref and current status
  531. if (!$error) {
  532. $this->ref = $num;
  533. $this->status = self::STATUS_VALIDATED;
  534. }
  535. if (!$error) {
  536. $this->db->commit();
  537. return 1;
  538. } else {
  539. $this->db->rollback();
  540. return -1;
  541. }
  542. }
  543. /**
  544. * Set draft status
  545. *
  546. * @param User $user Object user that modify
  547. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  548. * @return int <0 if KO, >0 if OK
  549. */
  550. public function setDraft($user, $notrigger = 0)
  551. {
  552. // Protection
  553. if ($this->status <= self::STATUS_DRAFT) {
  554. return 0;
  555. }
  556. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->financialreport->write))
  557. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->financialreport->financialreport_advance->validate))))
  558. {
  559. $this->error='Permission denied';
  560. return -1;
  561. }*/
  562. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'USERINVOICE_UNVALIDATE');
  563. }
  564. /**
  565. * Set cancel status
  566. *
  567. * @param User $user Object user that modify
  568. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  569. * @return int <0 if KO, 0=Nothing done, >0 if OK
  570. */
  571. public function cancel($user, $notrigger = 0)
  572. {
  573. // Protection
  574. if ($this->status != self::STATUS_VALIDATED) {
  575. return 0;
  576. }
  577. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->financialreport->write))
  578. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->financialreport->financialreport_advance->validate))))
  579. {
  580. $this->error='Permission denied';
  581. return -1;
  582. }*/
  583. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'USERINVOICE_CANCEL');
  584. }
  585. /**
  586. * Set back to validated status
  587. *
  588. * @param User $user Object user that modify
  589. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  590. * @return int <0 if KO, 0=Nothing done, >0 if OK
  591. */
  592. public function reopen($user, $notrigger = 0)
  593. {
  594. // Protection
  595. if ($this->status != self::STATUS_CANCELED) {
  596. return 0;
  597. }
  598. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->financialreport->write))
  599. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->financialreport->financialreport_advance->validate))))
  600. {
  601. $this->error='Permission denied';
  602. return -1;
  603. }*/
  604. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'USERINVOICE_REOPEN');
  605. }
  606. /**
  607. * Return a link to the object card (with optionaly the picto)
  608. *
  609. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  610. * @param string $option On what the link point to ('nolink', ...)
  611. * @param int $notooltip 1=Disable tooltip
  612. * @param string $morecss Add more css on link
  613. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  614. * @return string String with URL
  615. */
  616. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  617. {
  618. global $conf, $langs, $hookmanager;
  619. if (!empty($conf->dol_no_mouse_hover)) {
  620. $notooltip = 1; // Force disable tooltips
  621. }
  622. $result = '';
  623. $label = img_picto('', $this->picto).' <u>'.$langs->trans("UserInvoice").'</u>';
  624. if (isset($this->status)) {
  625. $label .= ' '.$this->getLibStatut(5);
  626. }
  627. $label .= '<br>';
  628. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  629. $url = dol_buildpath('/financialreport/userinvoice_card.php', 1).'?id='.$this->id;
  630. if ($option != 'nolink') {
  631. // Add param to save lastsearch_values or not
  632. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  633. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  634. $add_save_lastsearch_values = 1;
  635. }
  636. if ($url && $add_save_lastsearch_values) {
  637. $url .= '&save_lastsearch_values=1';
  638. }
  639. }
  640. $linkclose = '';
  641. if (empty($notooltip)) {
  642. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  643. $label = $langs->trans("ShowUserInvoice");
  644. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  645. }
  646. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  647. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  648. } else {
  649. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  650. }
  651. if ($option == 'nolink' || empty($url)) {
  652. $linkstart = '<span';
  653. } else {
  654. $linkstart = '<a href="'.$url.'"';
  655. }
  656. $linkstart .= $linkclose.'>';
  657. if ($option == 'nolink' || empty($url)) {
  658. $linkend = '</span>';
  659. } else {
  660. $linkend = '</a>';
  661. }
  662. $result .= $linkstart;
  663. if (empty($this->showphoto_on_popup)) {
  664. if ($withpicto) {
  665. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  666. }
  667. } else {
  668. if ($withpicto) {
  669. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  670. list($class, $module) = explode('@', $this->picto);
  671. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
  672. $filearray = dol_dir_list($upload_dir, "files");
  673. $filename = $filearray[0]['name'];
  674. if (!empty($filename)) {
  675. $pospoint = strpos($filearray[0]['name'], '.');
  676. $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  677. if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
  678. $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$module.'" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div></div>';
  679. } else {
  680. $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div>';
  681. }
  682. $result .= '</div>';
  683. } else {
  684. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  685. }
  686. }
  687. }
  688. if ($withpicto != 2) {
  689. $result .= $this->ref;
  690. }
  691. $result .= $linkend;
  692. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  693. global $action, $hookmanager;
  694. $hookmanager->initHooks(array('userinvoicedao'));
  695. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  696. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  697. if ($reshook > 0) {
  698. $result = $hookmanager->resPrint;
  699. } else {
  700. $result .= $hookmanager->resPrint;
  701. }
  702. return $result;
  703. }
  704. /**
  705. * Return the label of the status
  706. *
  707. * @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
  708. * @return string Label of status
  709. */
  710. public function getLabelStatus($mode = 0)
  711. {
  712. return $this->LibStatut($this->status, $mode);
  713. }
  714. /**
  715. * Return the label of the status
  716. *
  717. * @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
  718. * @return string Label of status
  719. */
  720. public function getLibStatut($mode = 0)
  721. {
  722. return $this->LibStatut($this->status, $mode);
  723. }
  724. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  725. /**
  726. * Return the status
  727. *
  728. * @param int $status Id status
  729. * @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
  730. * @return string Label of status
  731. */
  732. public function LibStatut($status, $mode = 0)
  733. {
  734. // phpcs:enable
  735. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  736. global $langs;
  737. //$langs->load("financialreport@financialreport");
  738. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  739. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  740. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  741. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  742. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  743. $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  744. }
  745. $statusType = 'status'.$status;
  746. //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
  747. if ($status == self::STATUS_CANCELED) {
  748. $statusType = 'status6';
  749. }
  750. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  751. }
  752. /**
  753. * Load the info information in the object
  754. *
  755. * @param int $id Id of object
  756. * @return void
  757. */
  758. public function info($id)
  759. {
  760. $sql = "SELECT rowid,";
  761. $sql .= " date_creation as datec, tms as datem,";
  762. $sql .= " fk_user_creat, fk_user_modif";
  763. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
  764. $sql .= " WHERE t.rowid = ".((int) $id);
  765. $result = $this->db->query($sql);
  766. if ($result) {
  767. if ($this->db->num_rows($result)) {
  768. $obj = $this->db->fetch_object($result);
  769. $this->id = $obj->rowid;
  770. $this->user_creation_id = $obj->fk_user_creat;
  771. $this->user_modification_id = $obj->fk_user_modif;
  772. if (!empty($obj->fk_user_valid)) {
  773. $this->user_validation_id = $obj->fk_user_valid;
  774. }
  775. $this->date_creation = $this->db->jdate($obj->datec);
  776. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  777. if (!empty($obj->datev)) {
  778. $this->date_validation = empty($obj->datev) ? '' : $this->db->jdate($obj->datev);
  779. }
  780. }
  781. $this->db->free($result);
  782. } else {
  783. dol_print_error($this->db);
  784. }
  785. }
  786. /**
  787. * Initialise object with example values
  788. * Id must be 0 if object instance is a specimen
  789. *
  790. * @return void
  791. */
  792. public function initAsSpecimen()
  793. {
  794. // Set here init that are not commonf fields
  795. // $this->property1 = ...
  796. // $this->property2 = ...
  797. $this->initAsSpecimenCommon();
  798. }
  799. /**
  800. * Create an array of lines
  801. *
  802. * @return array|int array of lines if OK, <0 if KO
  803. */
  804. public function getLinesArray()
  805. {
  806. $this->lines = array();
  807. $objectline = new UserInvoiceLine($this->db);
  808. $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_userinvoice = '.((int) $this->id)));
  809. if (is_numeric($result)) {
  810. $this->error = $objectline->error;
  811. $this->errors = $objectline->errors;
  812. return $result;
  813. } else {
  814. $this->lines = $result;
  815. return $this->lines;
  816. }
  817. }
  818. /**
  819. * Returns the reference to the following non used object depending on the active numbering module.
  820. *
  821. * @return string Object free reference
  822. */
  823. public function getNextNumRef()
  824. {
  825. global $langs, $conf;
  826. $langs->load("financialreport@financialreport");
  827. if (empty($conf->global->FINANCIALREPORT_USERINVOICE_ADDON)) {
  828. $conf->global->FINANCIALREPORT_USERINVOICE_ADDON = 'mod_userinvoice_standard';
  829. }
  830. if (!empty($conf->global->FINANCIALREPORT_USERINVOICE_ADDON)) {
  831. $mybool = false;
  832. $file = $conf->global->FINANCIALREPORT_USERINVOICE_ADDON.".php";
  833. $classname = $conf->global->FINANCIALREPORT_USERINVOICE_ADDON;
  834. // Include file with class
  835. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  836. foreach ($dirmodels as $reldir) {
  837. $dir = dol_buildpath($reldir."core/modules/financialreport/");
  838. // Load file with numbering class (if found)
  839. $mybool |= @include_once $dir.$file;
  840. }
  841. if ($mybool === false) {
  842. dol_print_error('', "Failed to include file ".$file);
  843. return '';
  844. }
  845. if (class_exists($classname)) {
  846. $obj = new $classname();
  847. $numref = $obj->getNextValue($this);
  848. if ($numref != '' && $numref != '-1') {
  849. return $numref;
  850. } else {
  851. $this->error = $obj->error;
  852. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  853. return "";
  854. }
  855. } else {
  856. print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
  857. return "";
  858. }
  859. } else {
  860. print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
  861. return "";
  862. }
  863. }
  864. /**
  865. * Create a document onto disk according to template module.
  866. *
  867. * @param string $modele Force template to use ('' to not force)
  868. * @param Translate $outputlangs objet lang a utiliser pour traduction
  869. * @param int $hidedetails Hide details of lines
  870. * @param int $hidedesc Hide description
  871. * @param int $hideref Hide ref
  872. * @param null|array $moreparams Array to provide more information
  873. * @return int 0 if KO, 1 if OK
  874. */
  875. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  876. {
  877. global $conf, $langs;
  878. $result = 0;
  879. $includedocgeneration = 0;
  880. $langs->load("financialreport@financialreport");
  881. if (!dol_strlen($modele)) {
  882. $modele = 'standard_userinvoice';
  883. if (!empty($this->model_pdf)) {
  884. $modele = $this->model_pdf;
  885. } elseif (!empty($conf->global->USERINVOICE_ADDON_PDF)) {
  886. $modele = $conf->global->USERINVOICE_ADDON_PDF;
  887. }
  888. }
  889. $modelpath = "core/modules/financialreport/doc/";
  890. if ($includedocgeneration && !empty($modele)) {
  891. $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  892. }
  893. return $result;
  894. }
  895. /**
  896. * Action executed by scheduler
  897. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  898. * Use public function doScheduledJob($param1, $param2, ...) to get parameters
  899. *
  900. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  901. */
  902. public function doScheduledJob()
  903. {
  904. global $conf, $langs;
  905. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  906. $error = 0;
  907. $this->output = '';
  908. $this->error = '';
  909. dol_syslog(__METHOD__, LOG_DEBUG);
  910. $now = dol_now();
  911. $this->db->begin();
  912. // ...
  913. $this->db->commit();
  914. return $error;
  915. }
  916. }
  917. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  918. /**
  919. * Class UserInvoiceLine. You can also remove this and generate a CRUD class for lines objects.
  920. */
  921. class UserInvoiceLine extends CommonObjectLine
  922. {
  923. // To complete with content of an object UserInvoiceLine
  924. // We should have a field rowid, fk_userinvoice and position
  925. /**
  926. * @var int Does object support extrafields ? 0=No, 1=Yes
  927. */
  928. public $isextrafieldmanaged = 0;
  929. /**
  930. * Constructor
  931. *
  932. * @param DoliDb $db Database handler
  933. */
  934. public function __construct(DoliDB $db)
  935. {
  936. $this->db = $db;
  937. }
  938. }