--- /tmp/dsg/dolibarr/htdocs/expensereport/class/github_19.0.3_api_expensereports.class.php +++ /tmp/dsg/dolibarr/htdocs/expensereport/class/client_api_expensereports.class.php @@ -4 +3,0 @@ - * Copyright (C) 2020 Frédéric France @@ -32,560 +31,536 @@ - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - public static $FIELDS = array( - 'fk_user_author' - ); - - /** - * @var ExpenseReport $expensereport {@type ExpenseReport} - */ - public $expensereport; - - - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - $this->expensereport = new ExpenseReport($this->db); - } - - /** - * Get properties of a Expense Report object - * - * Return an array with Expense Report informations - * - * @param int $id ID of Expense Report - * @return Object Object with cleaned properties - * - * @throws RestException - */ - public function get($id) - { - if (!DolibarrApiAccess::$user->rights->expensereport->lire) { - throw new RestException(401); - } - - $result = $this->expensereport->fetch($id); - if (!$result) { - throw new RestException(404, 'Expense report not found'); - } - - if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $this->expensereport->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->expensereport); - } - - /** - * List Expense Reports - * - * Get a list of Expense Reports - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $user_ids User ids filter field. Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" - * @param string $properties Restrict the data returned to theses properties. Ignored if empty. Comma separated list of properties names - * @return array Array of Expense Report objects - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '', $properties = '') - { - global $db, $conf; - - if (!DolibarrApiAccess::$user->rights->expensereport->lire) { - throw new RestException(401); - } - - $obj_ret = array(); - - // case of external user, $societe param is ignored and replaced by user's socid - //$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $societe; - - $sql = "SELECT t.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport AS t LEFT JOIN ".MAIN_DB_PREFIX."expensereport_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields - $sql .= ' WHERE t.entity IN ('.getEntity('expensereport').')'; - if ($user_ids) { - $sql .= " AND t.fk_user_author IN (".$this->db->sanitize($user_ids).")"; - } - - // Add sql filters - if ($sqlfilters) { - $errormessage = ''; - $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage); - if ($errormessage) { - throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage); - } - } - - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit + 1, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - $i = 0; - while ($i < $min) { - $obj = $this->db->fetch_object($result); - $expensereport_static = new ExpenseReport($this->db); - if ($expensereport_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($expensereport_static), $properties); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve Expense Report list : '.$this->db->lasterror()); - } - - return $obj_ret; - } - - /** - * Create Expense Report object - * - * @param array $request_data Request data - * @return int ID of Expense Report - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401, "Insuffisant rights"); - } - - // Check mandatory fields - $result = $this->_validate($request_data); - - foreach ($request_data as $field => $value) { - if ($field === 'caller') { - // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller - $this->expensereport->context['caller'] = $request_data['caller']; - continue; - } - - $this->expensereport->$field = $value; - } - /*if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->expensereport->lines = $lines; - }*/ - if ($this->expensereport->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating expensereport", array_merge(array($this->expensereport->error), $this->expensereport->errors)); - } - - return $this->expensereport->id; - } - - /** - * Get lines of an Expense Report - * - * @param int $id Id of Expense Report - * - * @url GET {id}/lines - * - * @return int - */ - /* - public function getLines($id) - { - if(! DolibarrApiAccess::$user->rights->expensereport->lire) { - throw new RestException(401); - } - - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->expensereport->getLinesArray(); - $result = array(); - foreach ($this->expensereport->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - */ - - /** - * Add a line to given Expense Report - * - * @param int $id Id of Expense Report to update - * @param array $request_data Expense Report data - * - * @url POST {id}/lines - * - * @return int - */ - /* - public function postLine($id, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } - - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $request_data = (object) $request_data; - - $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml'); - $request_data->label = sanitizeVal($request_data->label); - - $updateRes = $this->expensereport->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - $request_data->info_bits, - $request_data->fk_remise_except, - 'HT', - 0, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->array_options, - $request_data->fk_unit, - $this->element, - $request_data->id - ); - - if ($updateRes > 0) { - return $updateRes; - - } - return false; - } - */ - - /** - * Update a line to given Expense Report - * - * @param int $id Id of Expense Report to update - * @param int $lineid Id of line to update - * @param array $request_data Expense Report data - * - * @url PUT {id}/lines/{lineid} - * - * @return object - */ - /* - public function putLine($id, $lineid, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } - - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $request_data = (object) $request_data; - - $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml'); - $request_data->label = sanitizeVal($request_data->label); - - $updateRes = $this->expensereport->updateline( - $lineid, - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->remise_percent, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - 'HT', - $request_data->info_bits, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->fk_parent_line, - 0, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->special_code, - $request_data->array_options, - $request_data->fk_unit - ); - - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } - return false; - } - */ - - /** - * Delete a line of given Expense Report - * - * @param int $id Id of Expense Report to update - * @param int $lineid Id of line to delete - * - * @url DELETE {id}/lines/{lineid} - * - * @return int - */ - /* - public function deleteLine($id, $lineid) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } - - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - // TODO Check the lineid $lineid is a line of ojbect - - $updateRes = $this->expensereport->deleteline($lineid); - if ($updateRes == 1) { - return $this->get($id); - } - return false; - } - */ - - /** - * Update Expense Report general fields (won't touch lines of expensereport) - * - * @param int $id Id of Expense Report to update - * @param array $request_data Datas - * - * @return int - * - * @throws RestException 401 Not allowed - * @throws RestException 404 Expense report not found - * @throws RestException 500 System error - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } - - $result = $this->expensereport->fetch($id); - if (!$result) { - throw new RestException(404, 'expensereport not found'); - } - - if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - foreach ($request_data as $field => $value) { - if ($field == 'id') { - continue; - } - if ($field === 'caller') { - // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller - $this->expensereport->context['caller'] = $request_data['caller']; - continue; - } - - $this->expensereport->$field = $value; - } - - if ($this->expensereport->update(DolibarrApiAccess::$user) > 0) { - return $this->get($id); - } else { - throw new RestException(500, $this->expensereport->error); - } - } - - /** - * Delete Expense Report - * - * @param int $id Expense Report ID - * - * @return array - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->expensereport->supprimer) { - throw new RestException(401); - } - - $result = $this->expensereport->fetch($id); - if (!$result) { - throw new RestException(404, 'Expense Report not found'); - } - - if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - if (!$this->expensereport->delete(DolibarrApiAccess::$user)) { - throw new RestException(500, 'Error when delete Expense Report : '.$this->expensereport->error); - } - - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Expense Report deleted' - ) - ); - } - - /** - * Validate an Expense Report - * - * @param int $id Expense Report ID - * - * @url POST {id}/validate - * - * @return array - * FIXME An error 403 is returned if the request has an empty body. - * Error message: "Forbidden: Content type `text/plain` is not supported." - * Workaround: send this in the body - * { - * "idwarehouse": 0 - * } - */ - /* - public function validate($id, $idwarehouse=0) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } - - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - if( ! $this->expensereport->valid(DolibarrApiAccess::$user, $idwarehouse)) { - throw new RestException(500, 'Error when validate expensereport'); - } - - return array( - 'success' => array( - 'code' => 200, - 'message' => 'expensereport validated' - ) - ); - }*/ - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); - - unset($object->fk_statut); - unset($object->statut); - unset($object->user); - unset($object->thirdparty); - - unset($object->cond_reglement); - unset($object->shipping_method_id); - - unset($object->barcode_type); - unset($object->barcode_type_code); - unset($object->barcode_type_label); - unset($object->barcode_type_coder); - - unset($object->code_paiement); - unset($object->code_statut); - unset($object->fk_c_paiement); - unset($object->fk_incoterms); - unset($object->label_incoterms); - unset($object->location_incoterms); - unset($object->mode_reglement_id); - unset($object->cond_reglement_id); - - unset($object->name); - unset($object->lastname); - unset($object->firstname); - unset($object->civility_id); - unset($object->cond_reglement_id); - unset($object->contact); - unset($object->contact_id); - - unset($object->state); - unset($object->state_id); - unset($object->state_code); - unset($object->country); - unset($object->country_id); - unset($object->country_code); - - unset($object->note); // We already use note_public and note_pricate - - return $object; - } - - /** - * Validate fields before create or update object - * - * @param array $data Array with data to verify - * @return array - * @throws RestException - */ - private function _validate($data) - { - $expensereport = array(); - foreach (ExpenseReports::$FIELDS as $field) { - if (!isset($data[$field])) { - throw new RestException(400, "$field field missing"); - } - $expensereport[$field] = $data[$field]; - } - return $expensereport; - } + + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'fk_user_author' + ); + + /** + * @var ExpenseReport $expensereport {@type ExpenseReport} + */ + public $expensereport; + + + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + $this->db = $db; + $this->expensereport = new ExpenseReport($this->db); + } + + /** + * Get properties of a Expense Report object + * + * Return an array with Expense Report informations + * + * @param int $id ID of Expense Report + * @return array|mixed Data without useless information + * + * @throws RestException + */ + public function get($id) + { + if (!DolibarrApiAccess::$user->rights->expensereport->lire) { + throw new RestException(401); + } + + $result = $this->expensereport->fetch($id); + if (!$result) { + throw new RestException(404, 'Expense report not found'); + } + + if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $this->expensereport->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->expensereport); + } + + /** + * List Expense Reports + * + * Get a list of Expense Reports + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $user_ids User ids filter field. Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return array Array of Expense Report objects + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '') + { + global $db, $conf; + + $obj_ret = array(); + + // case of external user, $societe param is ignored and replaced by user's socid + //$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $societe; + + $sql = "SELECT t.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t"; + $sql .= ' WHERE t.entity IN ('.getEntity('expensereport').')'; + if ($user_ids) $sql .= " AND t.fk_user_author IN (".$user_ids.")"; + + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql .= $db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $db->plimit($limit + 1, $offset); + } + + $result = $db->query($sql); + + if ($result) + { + $num = $db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $db->fetch_object($result); + $expensereport_static = new ExpenseReport($db); + if ($expensereport_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($expensereport_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve Expense Report list : '.$db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No Expense Report found'); + } + return $obj_ret; + } + + /** + * Create Expense Report object + * + * @param array $request_data Request data + * @return int ID of Expense Report + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401, "Insuffisant rights"); + } + // Check mandatory fields + $result = $this->_validate($request_data); + + foreach ($request_data as $field => $value) { + $this->expensereport->$field = $value; + } + /*if (isset($request_data["lines"])) { + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->expensereport->lines = $lines; + }*/ + if ($this->expensereport->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating expensereport", array_merge(array($this->expensereport->error), $this->expensereport->errors)); + } + + return $this->expensereport->id; + } + + /** + * Get lines of an Expense Report + * + * @param int $id Id of Expense Report + * + * @url GET {id}/lines + * + * @return int + */ + /* + public function getLines($id) + { + if(! DolibarrApiAccess::$user->rights->expensereport->lire) { + throw new RestException(401); + } + + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->expensereport->getLinesArray(); + $result = array(); + foreach ($this->expensereport->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + */ + + /** + * Add a line to given Expense Report + * + * @param int $id Id of Expense Report to update + * @param array $request_data Expense Report data + * + * @url POST {id}/lines + * + * @return int + */ + /* + public function postLine($id, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } + + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->expensereport->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->array_options, + $request_data->fk_unit, + $this->element, + $request_data->id + ); + + if ($updateRes > 0) { + return $updateRes; + + } + return false; + } + */ + + /** + * Update a line to given Expense Report + * + * @param int $id Id of Expense Report to update + * @param int $lineid Id of line to update + * @param array $request_data Expense Report data + * + * @url PUT {id}/lines/{lineid} + * + * @return object + */ + /* + public function putLine($id, $lineid, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } + + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->expensereport->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->fk_parent_line, + 0, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->special_code, + $request_data->array_options, + $request_data->fk_unit + ); + + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + } + */ + + /** + * Delete a line of given Expense Report + * + * @param int $id Id of Expense Report to update + * @param int $lineid Id of line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return int + */ + /* + public function deleteLine($id, $lineid) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } + + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + // TODO Check the lineid $lineid is a line of ojbect + + $updateRes = $this->expensereport->deleteline($lineid); + if ($updateRes == 1) { + return $this->get($id); + } + return false; + } + */ + + /** + * Update Expense Report general fields (won't touch lines of expensereport) + * + * @param int $id Id of Expense Report to update + * @param array $request_data Datas + * + * @return int + * + * @throws RestException 401 Not allowed + * @throws RestException 404 Expense report not found + * @throws RestException 500 + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } + + $result = $this->expensereport->fetch($id); + if (!$result) { + throw new RestException(404, 'expensereport not found'); + } + + if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + foreach ($request_data as $field => $value) { + if ($field == 'id') continue; + $this->expensereport->$field = $value; + } + + if ($this->expensereport->update(DolibarrApiAccess::$user) > 0) + { + return $this->get($id); + } + else + { + throw new RestException(500, $this->expensereport->error); + } + } + + /** + * Delete Expense Report + * + * @param int $id Expense Report ID + * + * @return array + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->expensereport->supprimer) { + throw new RestException(401); + } + $result = $this->expensereport->fetch($id); + if (!$result) { + throw new RestException(404, 'Expense Report not found'); + } + + if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if (!$this->expensereport->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when delete Expense Report : '.$this->expensereport->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Expense Report deleted' + ) + ); + } + + /** + * Validate an Expense Report + * + * @param int $id Expense Report ID + * + * @url POST {id}/validate + * + * @return array + * FIXME An error 403 is returned if the request has an empty body. + * Error message: "Forbidden: Content type `text/plain` is not supported." + * Workaround: send this in the body + * { + * "idwarehouse": 0 + * } + */ + /* + public function validate($id, $idwarehouse=0) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if( ! $this->expensereport->valid(DolibarrApiAccess::$user, $idwarehouse)) { + throw new RestException(500, 'Error when validate expensereport'); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'expensereport validated' + ) + ); + }*/ + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); + + unset($object->fk_statut); + unset($object->statut); + unset($object->user); + unset($object->thirdparty); + + unset($object->cond_reglement); + unset($object->shipping_method_id); + + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); + + unset($object->code_paiement); + unset($object->code_statut); + unset($object->fk_c_paiement); + unset($object->fk_incoterms); + unset($object->label_incoterms); + unset($object->location_incoterms); + unset($object->mode_reglement_id); + unset($object->cond_reglement_id); + + unset($object->name); + unset($object->lastname); + unset($object->firstname); + unset($object->civility_id); + unset($object->cond_reglement_id); + unset($object->contact); + unset($object->contact_id); + + unset($object->state); + unset($object->state_id); + unset($object->state_code); + unset($object->country); + unset($object->country_id); + unset($object->country_code); + + unset($object->note); // We already use note_public and note_pricate + + return $object; + } + + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + private function _validate($data) + { + $expensereport = array(); + foreach (ExpenseReports::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $expensereport[$field] = $data[$field]; + } + return $expensereport; + } --- /tmp/dsg/dolibarr/htdocs/expensereport/class/github_19.0.3_expensereport.class.php +++ /tmp/dsg/dolibarr/htdocs/expensereport/class/client_expensereport.class.php @@ -6,2 +6,2 @@ - * Copyright (c) 2018-2023 Frédéric France - * Copyright (C) 2016-2020 Ferran Marcet + * Copyright (c) 2018 Frédéric France + * Copyright (C) 2016-2018 Ferran Marcet @@ -29 +28,0 @@ -require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php'; @@ -32 +30,0 @@ - @@ -39 +37 @@ - /** + /** @@ -44 +42 @@ - /** + /** @@ -49,82 +47,35 @@ - /** - * @var string table element line name - */ - public $table_element_line = 'expensereport_det'; - - /** - * @var string Fieldname with ID of parent key if this field has a parent - */ - public $fk_element = 'fk_expensereport'; - - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'trip'; - - /** - * @var ExpenseReportLine[] array of expensereport lines - */ - public $lines = array(); - - /** - * @var ExpenseReportLine expensereport lines - */ - public $line; - - public $date_debut; - - public $date_fin; - - /** - * @var int|string - */ - public $date_approbation; - - /** - * @var int ID - */ - public $fk_user; - - public $user_approve_id; - - /** - * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=paid, 99=denied - * - * @var int Status - */ - public $status; - - /** - * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=paid, 99=denied - * - * @var int Status - * @deprecated - */ - public $fk_statut; - - public $fk_c_paiement; - public $modepaymentid; - - public $paid; - - public $user_author_infos; - public $user_validator_infos; - - public $rule_warning_message; - - // ACTIONS - - // Create - public $date_create; - - /** - * @var int ID of user creator - */ - public $fk_user_creat; - - /** - * @var int ID of user who reclaim expense report - */ - public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - - // Update + public $table_element_line = 'expensereport_det'; + public $fk_element = 'fk_expensereport'; + + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'trip'; + + public $lines = array(); + + public $date_debut; + + public $date_fin; + + /** + * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=payed, 99=denied + * + * @var int Status + */ + public $status; + public $fk_statut; + + public $fk_c_paiement; + public $paid; + + public $user_author_infos; + public $user_validator_infos; + + // ACTIONS + + // Create + public $date_create; + public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + + // Update @@ -132,71 +83,28 @@ - public $fk_user_modif; - - // Refus - public $date_refuse; - public $detail_refuse; - public $fk_user_refuse; - - // Annulation - public $date_cancel; - public $detail_cancel; - - /** - * @var int ID of user who cancel expense report - */ - public $fk_user_cancel; - - /** - * @var int User that is defined to approve - */ - public $fk_user_validator; - - /** - * Validation date - * @var int - * @deprecated - * @see $date_valid - */ - public $datevalid; - - /** - * Validation date - * @var int - */ - public $date_valid; - - /** - * @var int ID of User making validation - */ - public $fk_user_valid; - public $user_valid_infos; - - // Approve - public $date_approve; - public $fk_user_approve; // User that has approved - - // Paiement - public $user_paid_infos; - - public $localtax1; // for backward compatibility (real field should be total_localtax1 defined into CommonObject) - public $localtax2; // for backward compatibility (real field should be total_localtax2 defined into CommonObject) - - public $labelStatus = array(); - public $labelStatusShort = array(); - - // Multicurrency - /** - * @var int Currency ID - */ - public $fk_multicurrency; - - /** - * @var string multicurrency code - */ - public $multicurrency_code; - public $multicurrency_tx; - public $multicurrency_total_ht; - public $multicurrency_total_tva; - public $multicurrency_total_ttc; - - - /** + public $fk_user_modif; + + // Refus + public $date_refuse; + public $detail_refuse; + public $fk_user_refuse; + + // Annulation + public $date_cancel; + public $detail_cancel; + public $fk_user_cancel; + + public $fk_user_validator; // User that is defined to approve + + // Validation + public $date_valid; // User making validation + public $fk_user_valid; + public $user_valid_infos; + + // Approve + public $date_approve; + public $fk_user_approve; // User that has approved + + // Paiement + public $user_paid_infos; + + + /** @@ -222,0 +131,5 @@ + * Classified refused + */ + const STATUS_REFUSED = 99; + + /** @@ -227,4 +139,0 @@ - /** - * Classified refused - */ - const STATUS_REFUSED = 99; @@ -258,2 +167,2 @@ - 'note_public' =>array('type'=>'html', 'label'=>'Note public', 'enabled'=>1, 'visible'=>0, 'position'=>150), - 'note_private' =>array('type'=>'html', 'label'=>'Note private', 'enabled'=>1, 'visible'=>0, 'position'=>155), + 'note_public' =>array('type'=>'text', 'label'=>'Note public', 'enabled'=>1, 'visible'=>0, 'position'=>150), + 'note_private' =>array('type'=>'text', 'label'=>'Note private', 'enabled'=>1, 'visible'=>0, 'position'=>155), @@ -279,157 +188,153 @@ - * Constructor - * - * @param DoliDB $db Handler acces base de donnees - */ - public function __construct($db) - { - $this->db = $db; - $this->total_ht = 0; - $this->total_ttc = 0; - $this->total_tva = 0; - $this->total_localtax1 = 0; - $this->total_localtax2 = 0; - $this->localtax1 = 0; // For backward compatibility - $this->localtax2 = 0; // For backward compatibility - $this->modepaymentid = 0; - - // List of language codes for status - $this->labelStatusShort = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); - $this->labelStatus = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); - } - - /** - * Create object in database - * - * @param User $user User that create - * @param int $notrigger Disable triggers - * @return int Return integer <0 if KO, >0 if OK - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs; - - $now = dol_now(); - - $error = 0; - - // Check parameters - if (empty($this->date_debut) || empty($this->date_fin)) { - $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date')); - return -1; - } - - $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - if (empty($fuserid)) { - $fuserid = $user->id; - } - - $this->db->begin(); - - $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." ("; - $sql .= "ref"; - $sql .= ",total_ht"; - $sql .= ",total_ttc"; - $sql .= ",total_tva"; - $sql .= ",date_debut"; - $sql .= ",date_fin"; - $sql .= ",date_create"; - $sql .= ",fk_user_creat"; - $sql .= ",fk_user_author"; - $sql .= ",fk_user_validator"; - $sql .= ",fk_user_approve"; - $sql .= ",fk_user_modif"; - $sql .= ",fk_statut"; - $sql .= ",fk_c_paiement"; - $sql .= ",paid"; - $sql .= ",note_public"; - $sql .= ",note_private"; - $sql .= ",entity"; - $sql .= ") VALUES("; - $sql .= "'(PROV)'"; - $sql .= ", ".price2num($this->total_ht, 'MT'); - $sql .= ", ".price2num($this->total_ttc, 'MT'); - $sql .= ", ".price2num($this->total_tva, 'MT'); - $sql .= ", '".$this->db->idate($this->date_debut)."'"; - $sql .= ", '".$this->db->idate($this->date_fin)."'"; - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", ".((int) $user->id); - $sql .= ", ".((int) $fuserid); - $sql .= ", ".($this->fk_user_validator > 0 ? ((int) $this->fk_user_validator) : "null"); - $sql .= ", ".($this->fk_user_approve > 0 ? ((int) $this->fk_user_approve) : "null"); - $sql .= ", ".($this->fk_user_modif > 0 ? ((int) $this->fk_user_modif) : "null"); - $sql .= ", ".($this->fk_statut > 1 ? ((int) $this->fk_statut) : 0); - $sql .= ", ".($this->modepaymentid ? ((int) $this->modepaymentid) : "null"); - $sql .= ", 0"; - $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null"); - $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null"); - $sql .= ", ".((int) $conf->entity); - $sql .= ")"; - - $result = $this->db->query($sql); - if ($result) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - $this->ref = '(PROV'.$this->id.')'; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id); - $resql = $this->db->query($sql); - if (!$resql) { - $this->error = $this->db->lasterror(); - $error++; - } - - if (!$error) { - if (is_array($this->lines) && count($this->lines) > 0) { - foreach ($this->lines as $line) { - // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array - //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. - if (!is_object($line)) { - $line = (object) $line; - $newndfline = new ExpenseReportLine($this->db); - $newndfline->fk_expensereport = $line->fk_expensereport; - $newndfline->fk_c_type_fees = $line->fk_c_type_fees; - $newndfline->fk_project = $line->fk_project; - $newndfline->vatrate = $line->vatrate; - $newndfline->vat_src_code = $line->vat_src_code; - $newndfline->localtax1_tx = $line->localtax1_tx; - $newndfline->localtax2_tx = $line->localtax2_tx; - $newndfline->localtax1_type = $line->localtax1_type; - $newndfline->localtax2_type = $line->localtax2_type; - $newndfline->comments = $line->comments; - $newndfline->qty = $line->qty; - $newndfline->value_unit = $line->value_unit; - $newndfline->total_ht = $line->total_ht; - $newndfline->total_ttc = $line->total_ttc; - $newndfline->total_tva = $line->total_tva; - $newndfline->total_localtax1 = $line->total_localtax1; - $newndfline->total_localtax2 = $line->total_localtax2; - $newndfline->date = $line->date; - $newndfline->rule_warning_message = $line->rule_warning_message; - $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat; - $newndfline->fk_ecm_files = $line->fk_ecm_files; - } else { - $newndfline = $line; - } - //$newndfline=new ExpenseReportLine($this->db); - $newndfline->fk_expensereport = $this->id; - $result = $newndfline->insert(); - if ($result < 0) { - $this->error = $newndfline->error; - $this->errors = $newndfline->errors; - $error++; - break; - } - } - } - } - - if (!$error) { - $result = $this->insertExtraFields(); - if ($result < 0) { - $error++; - } - } - - if (!$error) { - $result = $this->update_price(1); - if ($result > 0) { - if (!$notrigger) { + * Constructor + * + * @param DoliDB $db Handler acces base de donnees + */ + public function __construct($db) + { + $this->db = $db; + $this->total_ht = 0; + $this->total_ttc = 0; + $this->total_tva = 0; + $this->modepaymentid = 0; + + // List of language codes for status + $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); + $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); + $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5'); + } + + /** + * Create object in database + * + * @param User $user User that create + * @param int $notrigger Disable triggers + * @return int <0 if KO, >0 if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; + + $now = dol_now(); + + $error = 0; + + // Check parameters + if (empty($this->date_debut) || empty($this->date_fin)) + { + $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date')); + return -1; + } + + $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + if (empty($fuserid)) $fuserid = $user->id; + + $this->db->begin(); + + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." ("; + $sql .= "ref"; + $sql .= ",total_ht"; + $sql .= ",total_ttc"; + $sql .= ",total_tva"; + $sql .= ",date_debut"; + $sql .= ",date_fin"; + $sql .= ",date_create"; + $sql .= ",fk_user_author"; + $sql .= ",fk_user_validator"; + $sql .= ",fk_user_approve"; + $sql .= ",fk_user_modif"; + $sql .= ",fk_statut"; + $sql .= ",fk_c_paiement"; + $sql .= ",paid"; + $sql .= ",note_public"; + $sql .= ",note_private"; + $sql .= ",entity"; + $sql .= ") VALUES("; + $sql .= "'(PROV)'"; + $sql .= ", ".$this->total_ht; + $sql .= ", ".$this->total_ttc; + $sql .= ", ".$this->total_tva; + $sql .= ", '".$this->db->idate($this->date_debut)."'"; + $sql .= ", '".$this->db->idate($this->date_fin)."'"; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", ".$fuserid; + $sql .= ", ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); + $sql .= ", ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); + $sql .= ", ".($this->fk_user_modif > 0 ? $this->fk_user_modif : "null"); + $sql .= ", ".($this->fk_statut > 1 ? $this->fk_statut : 0); + $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null"); + $sql .= ", 0"; + $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null"); + $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null"); + $sql .= ", ".$conf->entity; + $sql .= ")"; + + $result = $this->db->query($sql); + if ($result) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); + $this->ref = '(PROV'.$this->id.')'; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + $resql = $this->db->query($sql); + if (!$resql) + { + $this->error = $this->db->lasterror(); + $error++; + } + + if (!$error) + { + if (is_array($this->lines) && count($this->lines) > 0) + { + foreach ($this->lines as $line) + { + // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array + //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. + if (!is_object($line)) { + $line = (object) $line; + $newndfline = new ExpenseReportLine($this->db); + $newndfline->fk_expensereport = $line->fk_expensereport; + $newndfline->fk_c_type_fees = $line->fk_c_type_fees; + $newndfline->fk_project = $line->fk_project; + $newndfline->vatrate = $line->vatrate; + $newndfline->vat_src_code = $line->vat_src_code; + $newndfline->comments = $line->comments; + $newndfline->qty = $line->qty; + $newndfline->value_unit = $line->value_unit; + $newndfline->total_ht = $line->total_ht; + $newndfline->total_ttc = $line->total_ttc; + $newndfline->total_tva = $line->total_tva; + $newndfline->date = $line->date; + $newndfline->rule_warning_message = $line->rule_warning_message; + $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat; + $newndfline->fk_ecm_files = $line->fk_ecm_files; + } + else { + $newndfline = $line; + } + //$newndfline=new ExpenseReportLine($this->db); + $newndfline->fk_expensereport = $this->id; + $result = $newndfline->insert(); + if ($result < 0) + { + $this->error = $newndfline->error; + $error++; + break; + } + } + } + } + + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) $error++; + } + + if (!$error) + { + $result = $this->update_price(); + if ($result > 0) + { + if (!$notrigger) + { @@ -445 +350,2 @@ - if (empty($error)) { + if (empty($error)) + { @@ -448 +354,3 @@ - } else { + } + else + { @@ -452,19 +360,26 @@ - } else { - $this->db->rollback(); - return -3; - } - } else { - dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } else { - $this->error = $this->db->lasterror()." sql=".$sql; - $this->db->rollback(); - return -1; - } - } - - /** - * Load an object from its id and create a new one in database - * + } + else + { + $this->db->rollback(); + return -3; + } + } + else + { + dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } + else + { + $this->error = $this->db->lasterror()." sql=".$sql; + $this->db->rollback(); + return -1; + } + } + + + /** + * Load an object from its id and create a new one in database + * @@ -472,79 +387,69 @@ - * @param int $fk_user_author Id of new user - * @return int New id of clone - */ - public function createFromClone(User $user, $fk_user_author) - { - global $hookmanager; - - $error = 0; - - if (empty($fk_user_author)) { - $fk_user_author = $user->id; - } - - $this->db->begin(); - - // get extrafields so they will be clone - //foreach($this->lines as $line) - //$line->fetch_optionals(); - - // Load source object - $objFrom = clone $this; - - $this->id = 0; - $this->ref = ''; - $this->status = 0; - $this->fk_statut = 0; // deprecated - - // Clear fields - $this->fk_user_creat = $user->id; - $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - $this->fk_user_valid = ''; - $this->date_create = ''; - $this->date_creation = ''; - $this->date_validation = ''; - - // Remove link on lines to a joined file - if (is_array($this->lines) && count($this->lines) > 0) { - foreach ($this->lines as $key => $line) { - $this->lines[$key]->fk_ecm_files = 0; - } - } - - // Create clone - $this->context['createfromclone'] = 'createfromclone'; - $result = $this->create($user); - if ($result < 0) { - $error++; - } - - if (!$error) { - // Hook of thirdparty module - if (is_object($hookmanager)) { - $parameters = array('objFrom'=>$objFrom); - $action = ''; - $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) { - $this->setErrorsFromObject($hookmanager); - $error++; - } - } - } - - unset($this->context['createfromclone']); - - // End - if (!$error) { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } - - - /** - * update - * - * @param User $user User making change + * @param int $fk_user_author Id of new user + * @return int New id of clone + */ + public function createFromClone(User $user, $fk_user_author) + { + global $hookmanager; + + $error = 0; + + if (empty($fk_user_author)) $fk_user_author = $user->id; + + $this->db->begin(); + + // get extrafields so they will be clone + //foreach($this->lines as $line) + //$line->fetch_optionals(); + + // Load source object + $objFrom = clone $this; + + $this->id = 0; + $this->ref = ''; + $this->status = 0; + $this->fk_statut = 0; + + // Clear fields + $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + $this->fk_user_valid = ''; + $this->date_create = ''; + $this->date_creation = ''; + $this->date_validation = ''; + + // Create clone + $this->context['createfromclone'] = 'createfromclone'; + $result = $this->create($user); + if ($result < 0) $error++; + + if (!$error) + { + // Hook of thirdparty module + if (is_object($hookmanager)) + { + $parameters = array('objFrom'=>$objFrom); + $action = ''; + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) $error++; + } + } + + unset($this->context['createfromclone']); + + // End + if (!$error) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1; + } + } + + + /** + * update + * + * @param User $user User making change @@ -552,6 +457,6 @@ - * @param User $userofexpensereport New user we want to have the expense report on. - * @return int Return integer <0 if KO, >0 if OK - */ - public function update($user, $notrigger = 0, $userofexpensereport = null) - { - global $langs; + * @param User $userofexpensereport New user we want to have the expense report on. + * @return int <0 if KO, >0 if OK + */ + public function update($user, $notrigger = 0, $userofexpensereport = null) + { + global $langs; @@ -562,24 +467,27 @@ - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " total_ht = ".$this->total_ht; - $sql .= " , total_ttc = ".$this->total_ttc; - $sql .= " , total_tva = ".$this->total_tva; - $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'"; - $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'"; - if ($userofexpensereport && is_object($userofexpensereport)) { - $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. - } - $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); - $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null"); - $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); - $sql .= " , fk_user_modif = ".$user->id; - $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0'); - $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null"); - $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''"); - $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''"); - $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''"); - $sql .= " WHERE rowid = ".((int) $this->id); - - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) { - if (!$notrigger) { + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$this->total_ht; + $sql .= " , total_ttc = ".$this->total_ttc; + $sql .= " , total_tva = ".$this->total_tva; + $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'"; + $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'"; + if ($userofexpensereport && is_object($userofexpensereport)) + { + $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. + } + $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); + $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null"); + $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); + $sql .= " , fk_user_modif = ".$user->id; + $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0'); + $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null"); + $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''"); + $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''"); + $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''"); + $sql .= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + if (!$notrigger) + { @@ -587 +495 @@ - $result = $this->call_trigger('EXPENSE_REPORT_MODIFY', $user); + $result = $this->call_trigger('EXPENSE_REPORT_UPDATE', $user); @@ -595 +503,2 @@ - if (empty($error)) { + if (empty($error)) + { @@ -598 +507,3 @@ - } else { + } + else + { @@ -603 +514,3 @@ - } else { + } + else + { @@ -605,139 +518,109 @@ - $this->error = $this->db->error(); - return -1; - } - } - - /** - * Load an object from database - * - * @param int $id Id {@min 1} - * @param string $ref Ref {@name ref} - * @return int Return integer <0 if KO, >0 if OK - */ - public function fetch($id, $ref = '') - { - global $conf; - - $sql = "SELECT d.rowid, d.entity, d.ref, d.note_public, d.note_private,"; // DEFAULT - $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS - $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS - $sql .= " d.total_ht, d.total_ttc, d.total_tva,"; - $sql .= " d.localtax1 as total_localtax1, d.localtax2 as total_localtax2,"; - $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime) - $sql .= " d.fk_user_creat, d.fk_user_author, d.fk_user_modif, d.fk_user_validator,"; - $sql .= " d.fk_user_valid, d.fk_user_approve,"; - $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid"; - $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d"; - if ($ref) { - $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'"; - } else { - $sql .= " WHERE d.rowid = ".((int) $id); - } - //$sql.= $restrict; - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $obj = $this->db->fetch_object($resql); - if ($obj) { - $this->id = $obj->rowid; - $this->ref = $obj->ref; - - $this->entity = $obj->entity; - - $this->total_ht = $obj->total_ht; - $this->total_tva = $obj->total_tva; - $this->total_ttc = $obj->total_ttc; - $this->localtax1 = $obj->total_localtax1; // For backward compatibility - $this->localtax2 = $obj->total_localtax2; // For backward compatibility - $this->total_localtax1 = $obj->total_localtax1; - $this->total_localtax2 = $obj->total_localtax2; - - $this->note_public = $obj->note_public; - $this->note_private = $obj->note_private; - $this->detail_refuse = $obj->detail_refuse; - $this->detail_cancel = $obj->detail_cancel; - - $this->date_debut = $this->db->jdate($obj->date_debut); - $this->date_fin = $this->db->jdate($obj->date_fin); - $this->date_valid = $this->db->jdate($obj->date_valid); - $this->date_approve = $this->db->jdate($obj->date_approve); - $this->date_create = $this->db->jdate($obj->date_create); - $this->date_modif = $this->db->jdate($obj->date_modif); - $this->date_refuse = $this->db->jdate($obj->date_refuse); - $this->date_cancel = $this->db->jdate($obj->date_cancel); - - $this->fk_user_creat = $obj->fk_user_creat; - $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - $this->fk_user_modif = $obj->fk_user_modif; - $this->fk_user_validator = $obj->fk_user_validator; - $this->fk_user_valid = $obj->fk_user_valid; - $this->fk_user_refuse = $obj->fk_user_refuse; - $this->fk_user_cancel = $obj->fk_user_cancel; - $this->fk_user_approve = $obj->fk_user_approve; - - $user_author = new User($this->db); - if ($this->fk_user_author > 0) { - $user_author->fetch($this->fk_user_author); - } - - $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname); - - $user_approver = new User($this->db); - if ($this->fk_user_approve > 0) { - $user_approver->fetch($this->fk_user_approve); - } elseif ($this->fk_user_validator > 0) { - $user_approver->fetch($this->fk_user_validator); // For backward compatibility - } - $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname); - - $this->fk_statut = $obj->status; // deprecated - $this->status = $obj->status; - $this->fk_c_paiement = $obj->fk_c_paiement; - $this->paid = $obj->paid; - - if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED) { - $user_valid = new User($this->db); - if ($this->fk_user_valid > 0) { - $user_valid->fetch($this->fk_user_valid); - } - $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname); - } - - $this->fetch_optionals(); - - $result = $this->fetch_lines(); - - return $result; - } else { - return 0; - } - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Classify the expense report as paid - * - * @deprecated - * @see setPaid() - * @param int $id Id of expense report - * @param user $fuser User making change - * @param int $notrigger Disable triggers - * @return int Return integer <0 if KO, >0 if OK - */ - public function set_paid($id, $fuser, $notrigger = 0) - { - // phpcs:enable - dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE); - return $this->setPaid($id, $fuser, $notrigger); - } - - /** - * Classify the expense report as paid - * - * @param int $id Id of expense report - * @param user $fuser User making change + $this->error = $this->db->error(); + return -1; + } + } + + /** + * Load an object from database + * + * @param int $id Id {@min 1} + * @param string $ref Ref {@name ref} + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $ref = '') + { + global $conf; + + $sql = "SELECT d.rowid, d.ref, d.note_public, d.note_private,"; // DEFAULT + $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS + $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS + $sql .= " d.total_ht, d.total_ttc, d.total_tva,"; // TOTAUX (int) + $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime) + $sql .= " d.fk_user_author, d.fk_user_modif, d.fk_user_validator,"; + $sql .= " d.fk_user_valid, d.fk_user_approve,"; + $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d"; + if ($ref) $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'"; + else $sql .= " WHERE d.rowid = ".$id; + //$sql.= $restrict; + + dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) + { + $this->id = $obj->rowid; + $this->ref = $obj->ref; + $this->total_ht = $obj->total_ht; + $this->total_tva = $obj->total_tva; + $this->total_ttc = $obj->total_ttc; + $this->note_public = $obj->note_public; + $this->note_private = $obj->note_private; + $this->detail_refuse = $obj->detail_refuse; + $this->detail_cancel = $obj->detail_cancel; + + $this->date_debut = $this->db->jdate($obj->date_debut); + $this->date_fin = $this->db->jdate($obj->date_fin); + $this->date_valid = $this->db->jdate($obj->date_valid); + $this->date_approve = $this->db->jdate($obj->date_approve); + $this->date_create = $this->db->jdate($obj->date_create); + $this->date_modif = $this->db->jdate($obj->date_modif); + $this->date_refuse = $this->db->jdate($obj->date_refuse); + $this->date_cancel = $this->db->jdate($obj->date_cancel); + + $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + $this->fk_user_modif = $obj->fk_user_modif; + $this->fk_user_validator = $obj->fk_user_validator; + $this->fk_user_valid = $obj->fk_user_valid; + $this->fk_user_refuse = $obj->fk_user_refuse; + $this->fk_user_cancel = $obj->fk_user_cancel; + $this->fk_user_approve = $obj->fk_user_approve; + + $user_author = new User($this->db); + if ($this->fk_user_author > 0) $user_author->fetch($this->fk_user_author); + + $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname); + + $user_approver = new User($this->db); + if ($this->fk_user_approve > 0) $user_approver->fetch($this->fk_user_approve); + elseif ($this->fk_user_validator > 0) $user_approver->fetch($this->fk_user_validator); // For backward compatibility + $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname); + + $this->fk_statut = $obj->status; // deprecated + $this->status = $obj->status; + $this->fk_c_paiement = $obj->fk_c_paiement; + $this->paid = $obj->paid; + + if ($this->fk_statut == self::STATUS_APPROVED || $this->fk_statut == self::STATUS_CLOSED) + { + $user_valid = new User($this->db); + if ($this->fk_user_valid > 0) $user_valid->fetch($this->fk_user_valid); + $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname); + } + + $this->lines = array(); + + $result = $this->fetch_lines(); + + return $result; + } + else + { + return 0; + } + } + else + { + $this->error = $this->db->lasterror(); + return -1; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Classify the expense report as paid + * + * @param int $id Id of expense report + * @param user $fuser User making change @@ -745,4 +628,5 @@ - * @return int Return integer <0 if KO, >0 if OK - */ - public function setPaid($id, $fuser, $notrigger = 0) - { + * @return int <0 if KO, >0 if OK + */ + public function set_paid($id, $fuser, $notrigger = 0) + { + // phpcs:enable @@ -752,9 +636,12 @@ - $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport"; - $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1"; - $sql .= " WHERE rowid = ".((int) $id)." AND fk_statut = ".self::STATUS_APPROVED; - - dol_syslog(get_class($this)."::setPaid", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - if ($this->db->affected_rows($resql)) { - if (!$notrigger) { + $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport"; + $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1"; + $sql .= " WHERE rowid = ".$id." AND fk_statut = ".self::STATUS_APPROVED; + + dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->affected_rows($resql)) + { + if (!$notrigger) + { @@ -770 +657,2 @@ - if (empty($error)) { + if (empty($error)) + { @@ -773 +661,3 @@ - } else { + } + else + { @@ -778 +668,3 @@ - } else { + } + else + { @@ -780,3 +672,5 @@ - return 0; - } - } else { + return 0; + } + } + else + { @@ -784,476 +678,460 @@ - dol_print_error($this->db); - return -1; - } - } - - /** - * Returns the label status - * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto - * @return string Label - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut($this->status, $mode); - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Returns the label of a status - * - * @param int $status ID status - * @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 - * @return string Label - */ - public function LibStatut($status, $mode = 0) - { - // phpcs:enable - global $langs; - - $labelStatus = $langs->transnoentitiesnoconv($this->labelStatus[$status]); - $labelStatusShort = $langs->transnoentitiesnoconv($this->labelStatusShort[$status]); - - $statuslogo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5'); - - $statusType = $statuslogo[$status]; - - return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); - } - - - /** - * Load information on object - * - * @param int $id Id of object - * @return void - */ - public function info($id) - { - global $conf; - - $sql = "SELECT f.rowid,"; - $sql .= " f.date_create as datec,"; - $sql .= " f.tms as date_modification,"; - $sql .= " f.date_valid as datev,"; - $sql .= " f.date_approve as datea,"; - $sql .= " f.fk_user_creat as fk_user_creation,"; - $sql .= " f.fk_user_author as fk_user_author,"; - $sql .= " f.fk_user_modif as fk_user_modification,"; - $sql .= " f.fk_user_valid,"; - $sql .= " f.fk_user_approve"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f"; - $sql .= " WHERE f.rowid = ".((int) $id); - $sql .= " AND f.entity = ".$conf->entity; - - $resql = $this->db->query($sql); - if ($resql) { - if ($this->db->num_rows($resql)) { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_modification = $this->db->jdate($obj->date_modification); - $this->date_validation = $this->db->jdate($obj->datev); - $this->date_approbation = $this->db->jdate($obj->datea); - - $this->user_creation_id = $obj->fk_user_author; - $this->user_creation_id = $obj->fk_user_creation; - $this->user_validation_id = $obj->fk_user_valid; - $this->user_modification_id = $obj->fk_user_modification; - $this->user_approve_id = $obj->fk_user_approve; - } - $this->db->free($resql); - } else { - dol_print_error($this->db); - } - } - - - - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - public function initAsSpecimen() - { - global $user, $langs, $conf; - - $now = dol_now(); - - // Initialise parametres - $this->id = 0; - $this->ref = 'SPECIMEN'; - $this->specimen = 1; - $this->entity = 1; - $this->date_create = $now; - $this->date_debut = $now; - $this->date_fin = $now; - $this->date_valid = $now; - $this->date_approve = $now; - - $type_fees_id = 2; // TF_TRIP - - $this->status = 5; - $this->fk_statut = 5; - - $this->fk_user_author = $user->id; - $this->fk_user_validator = $user->id; - $this->fk_user_valid = $user->id; - $this->fk_user_approve = $user->id; - - $this->note_private = 'Private note'; - $this->note_public = 'SPECIMEN'; - $nbp = 5; - $xnbp = 0; - while ($xnbp < $nbp) { - $line = new ExpenseReportLine($this->db); - $line->comments = $langs->trans("Comment")." ".$xnbp; - $line->date = ($now - 3600 * (1 + $xnbp)); - $line->total_ht = 100; - $line->total_tva = 20; - $line->total_ttc = 120; - $line->qty = 1; - $line->vatrate = 20; - $line->value_unit = 120; - $line->fk_expensereport = 0; - $line->type_fees_code = 'TRA'; - $line->fk_c_type_fees = $type_fees_id; - - $line->projet_ref = 'ABC'; - - $this->lines[$xnbp] = $line; - $xnbp++; - - $this->total_ht += $line->total_ht; - $this->total_tva += $line->total_tva; - $this->total_ttc += $line->total_ttc; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * fetch_line_by_project - * - * @param int $projectid Project id - * @param User $user User - * @return int Return integer <0 if KO, >0 if OK - */ - public function fetch_line_by_project($projectid, $user = '') - { - // phpcs:enable - global $conf, $db, $langs; - - $langs->load('trips'); - - if ($user->hasRight('expensereport', 'lire')) { - $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de"; - $sql .= " WHERE de.fk_projet = ".((int) $projectid); - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $i = 0; - $total_HT = 0; - $total_TTC = 0; - - while ($i < $num) { - $objp = $this->db->fetch_object($result); - - $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut as status"; - $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d"; - $sql2 .= " WHERE d.rowid = ".((int) $objp->fk_expensereport); - - $result2 = $this->db->query($sql2); - $obj = $this->db->fetch_object($result2); - - $objp->fk_user_author = $obj->fk_user_author; - $objp->ref = $obj->ref; - $objp->fk_c_expensereport_status = $obj->status; - $objp->rowid = $obj->rowid; - - $total_HT = $total_HT + $objp->total_ht; - $total_TTC = $total_TTC + $objp->total_ttc; - $author = new User($this->db); - $author->fetch($objp->fk_user_author); - - print ''; - print ''.$objp->ref_num.''; - print ''.dol_print_date($objp->date, 'day').''; - print ''.$author->getNomUrl(1).''; - print ''.$objp->comments.''; - print ''.price($objp->total_ht).''; - print ''.price($objp->total_ttc).''; - print ''; - - switch ($objp->fk_c_expensereport_status) { - case 4: - print img_picto($langs->trans('StatusOrderCanceled'), 'statut5'); - break; - case 1: - print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0'); - break; - case 2: - print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3'); - break; - case 5: - print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3'); - break; - case 6: - print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4'); - break; - } - /* - if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5'); - if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0'); - if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1'); - if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3'); - if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); - if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6'); - */ - print ''; - print ''; - - $i++; - } - - print ''.$langs->trans("Number").': '.$i.''; - print ''.$langs->trans("TotalHT").' : '.price($total_HT).''; - print ''.$langs->trans("TotalTTC").' : '.price($total_TTC).''; - print ' '; - print ''; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } - - return 0; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * fetch_lines - * - * @return int Return integer <0 if OK, >0 if KO - */ - public function fetch_lines() - { - // phpcs:enable - global $conf; - - $this->lines = array(); - - $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,'; - $sql .= " de.".$this->fk_element.", de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project,"; - $sql .= ' de.tva_tx, de.vat_src_code,'; - $sql .= ' de.localtax1_tx, de.localtax2_tx, de.localtax1_type, de.localtax2_type,'; - $sql .= ' de.fk_ecm_files,'; - $sql .= ' de.total_ht, de.total_tva, de.total_ttc,'; - $sql .= ' de.total_localtax1, de.total_localtax2, de.rule_warning_message,'; - $sql .= ' ctf.code as code_type_fees, ctf.label as label_type_fees, ctf.accountancy_code as accountancy_code_type_fees,'; - $sql .= ' p.ref as ref_projet, p.title as title_projet'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid'; - $sql .= " WHERE de.".$this->fk_element." = ".((int) $this->id); - if (getDolGlobalString('EXPENSEREPORT_LINES_SORTED_BY_ROWID')) { - $sql .= ' ORDER BY de.rang ASC, de.rowid ASC'; - } else { - $sql .= ' ORDER BY de.rang ASC, de.date ASC'; - } - - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) { - $objp = $this->db->fetch_object($resql); - - $deplig = new ExpenseReportLine($this->db); - - $deplig->rowid = $objp->rowid; - $deplig->id = $objp->rowid; - $deplig->comments = $objp->comments; - $deplig->qty = $objp->qty; - $deplig->value_unit = $objp->value_unit; - $deplig->date = $objp->date; - $deplig->dates = $this->db->jdate($objp->date); - - $deplig->fk_expensereport = $objp->fk_expensereport; - $deplig->fk_c_type_fees = $objp->fk_c_type_fees; - $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; - $deplig->fk_projet = $objp->fk_project; // deprecated - $deplig->fk_project = $objp->fk_project; - $deplig->fk_ecm_files = $objp->fk_ecm_files; - - $deplig->total_ht = $objp->total_ht; - $deplig->total_tva = $objp->total_tva; - $deplig->total_ttc = $objp->total_ttc; - $deplig->total_localtax1 = $objp->total_localtax1; - $deplig->total_localtax2 = $objp->total_localtax2; - - $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees; - $deplig->type_fees_libelle = $objp->label_type_fees; - $deplig->type_fees_accountancy_code = $objp->accountancy_code_type_fees; - - $deplig->tva_tx = $objp->tva_tx; - $deplig->vatrate = $objp->tva_tx; - $deplig->vat_src_code = $objp->vat_src_code; - $deplig->localtax1_tx = $objp->localtax1_tx; - $deplig->localtax2_tx = $objp->localtax2_tx; - $deplig->localtax1_type = $objp->localtax1_type; - $deplig->localtax2_type = $objp->localtax2_type; - - $deplig->projet_ref = $objp->ref_projet; - $deplig->projet_title = $objp->title_projet; - - $deplig->rule_warning_message = $objp->rule_warning_message; - - $deplig->rang = $objp->rang; - - $this->lines[$i] = $deplig; - - $i++; - } - $this->db->free($resql); - return 1; - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR); - return -3; - } - } - - - /** - * Delete object in database - * - * @param User|null $user User that delete - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @return int Return integer <0 if KO, >0 if OK - */ - public function delete(User $user = null, $notrigger = false) - { - global $conf; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - $error = 0; - - $this->db->begin(); - - if (!$notrigger) { - // Call trigger - $result = $this->call_trigger('EXPENSE_REPORT_DELETE', $user); - if ($result < 0) { - $error++; - } - // End call triggers - } - - // Delete extrafields of lines and lines - if (!$error && !empty($this->table_element_line)) { - $tabletodelete = $this->table_element_line; - //$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).")"; - $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id); - if (!$this->db->query($sql)) { - $error++; - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR); - } - } - - if (!$error) { - // Delete linked object - $res = $this->deleteObjectLinked(); - if ($res < 0) { - $error++; - } - } - - if (!$error) { - // Delete linked contacts - $res = $this->delete_linked_contact(); - if ($res < 0) { - $error++; - } - } - - // Removed extrafields of object - if (!$error) { - $result = $this->deleteExtraFields(); - if ($result < 0) { - $error++; - dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR); - } - } - - // Delete main record - if (!$error) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id); - $res = $this->db->query($sql); - if (!$res) { - $error++; - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR); - } - } - - // Delete record into ECM index and physically - if (!$error) { - $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive - $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive - if (!$res) { - $error++; - } - } - - if (!$error) { - // We remove directory - $ref = dol_sanitizeFileName($this->ref); - if ($conf->expensereport->multidir_output[$this->entity] && !empty($this->ref)) { - $dir = $conf->expensereport->multidir_output[$this->entity]."/".$ref; - $file = $dir."/".$ref.".pdf"; - if (file_exists($file)) { - dol_delete_preview($this); - - if (!dol_delete_file($file, 0, 0, 0, $this)) { - $this->error = 'ErrorFailToDeleteFile'; - $this->errors[] = $this->error; - $this->db->rollback(); - return 0; - } - } - if (file_exists($dir)) { - $res = @dol_delete_dir_recursive($dir); - if (!$res) { - $this->error = 'ErrorFailToDeleteDir'; - $this->errors[] = $this->error; - $this->db->rollback(); - return 0; - } - } - } - } - - if (!$error) { - dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } - - /** - * Set to status validate - * - * @param User $fuser User + dol_print_error($this->db); + return -1; + } + } + + /** + * Returns the label status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string Label + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Returns the label of a statut + * + * @param int $status id statut + * @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 + * @return string Label + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + global $langs; + + $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]); + $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]); + + $statusType = $this->statuts_logo[$status]; + + return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); + } + + + /** + * Load information on object + * + * @param int $id Id of object + * @return void + */ + public function info($id) + { + global $conf; + + $sql = "SELECT f.rowid,"; + $sql .= " f.date_create as datec,"; + $sql .= " f.tms as date_modification,"; + $sql .= " f.date_valid as datev,"; + $sql .= " f.date_approve as datea,"; + //$sql.= " f.fk_user_author as fk_user_creation,"; // This is not user of creation but user the expense is for. + $sql .= " f.fk_user_modif as fk_user_modification,"; + $sql .= " f.fk_user_valid,"; + $sql .= " f.fk_user_approve"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f"; + $sql .= " WHERE f.rowid = ".$id; + $sql .= " AND f.entity = ".$conf->entity; + + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->date_modification); + $this->date_validation = $this->db->jdate($obj->datev); + $this->date_approbation = $this->db->jdate($obj->datea); + + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + + if ($obj->fk_user_creation) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_creation); + $this->user_creation = $cuser; + } + if ($obj->fk_user_valid) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + if ($obj->fk_user_modification) + { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_modification); + $this->user_modification = $muser; + } + if ($obj->fk_user_approve) + { + $auser = new User($this->db); + $auser->fetch($obj->fk_user_approve); + $this->user_approve = $auser; + } + } + $this->db->free($resql); + } + else + { + dol_print_error($this->db); + } + } + + + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + public function initAsSpecimen() + { + global $user, $langs, $conf; + + $now = dol_now(); + + // Initialise parametres + $this->id = 0; + $this->ref = 'SPECIMEN'; + $this->specimen = 1; + $this->date_create = $now; + $this->date_debut = $now; + $this->date_fin = $now; + $this->date_valid = $now; + $this->date_approve = $now; + + $type_fees_id = 2; // TF_TRIP + + $this->status = 5; + $this->fk_statut = 5; + + $this->fk_user_author = $user->id; + $this->fk_user_validator = $user->id; + $this->fk_user_valid = $user->id; + $this->fk_user_approve = $user->id; + + $this->note_private = 'Private note'; + $this->note_public = 'SPECIMEN'; + $nbp = 5; + $xnbp = 0; + while ($xnbp < $nbp) { + $line = new ExpenseReportLine($this->db); + $line->comments = $langs->trans("Comment")." ".$xnbp; + $line->date = ($now - 3600 * (1 + $xnbp)); + $line->total_ht = 100; + $line->total_tva = 20; + $line->total_ttc = 120; + $line->qty = 1; + $line->vatrate = 20; + $line->value_unit = 120; + $line->fk_expensereport = 0; + $line->type_fees_code = 'TRA'; + $line->fk_c_type_fees = $type_fees_id; + + $line->projet_ref = 'ABC'; + + $this->lines[$xnbp] = $line; + $xnbp++; + + $this->total_ht += $line->total_ht; + $this->total_tva += $line->total_tva; + $this->total_ttc += $line->total_ttc; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * fetch_line_by_project + * + * @param int $projectid Project id + * @param User $user User + * @return int <0 if KO, >0 if OK + */ + public function fetch_line_by_project($projectid, $user = '') + { + // phpcs:enable + global $conf, $db, $langs; + + $langs->load('trips'); + + if ($user->rights->expensereport->lire) { + $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de"; + $sql .= " WHERE de.fk_projet = ".$projectid; + + dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + $total_HT = 0; + $total_TTC = 0; + + while ($i < $num) + { + $objp = $db->fetch_object($result); + + $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut"; + $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d"; + $sql2 .= " WHERE d.rowid = '".$objp->fk_expensereport."'"; + + $result2 = $db->query($sql2); + $obj = $db->fetch_object($result2); + + $objp->fk_user_author = $obj->fk_user_author; + $objp->ref = $obj->ref; + $objp->fk_c_expensereport_status = $obj->fk_statut; + $objp->rowid = $obj->rowid; + + $total_HT = $total_HT + $objp->total_ht; + $total_TTC = $total_TTC + $objp->total_ttc; + $author = new User($db); + $author->fetch($objp->fk_user_author); + + print ''; + print ''.$objp->ref_num.''; + print ''.dol_print_date($objp->date, 'day').''; + print ''.$author->getNomUrl(1).''; + print ''.$objp->comments.''; + print ''.price($objp->total_ht).''; + print ''.price($objp->total_ttc).''; + print ''; + + switch ($objp->fk_c_expensereport_status) { + case 4: + print img_picto($langs->trans('StatusOrderCanceled'), 'statut5'); + break; + case 1: + print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0'); + break; + case 2: + print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3'); + break; + case 5: + print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3'); + break; + case 6: + print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4'); + break; + } + /* + if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5'); + if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0'); + if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1'); + if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3'); + if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); + if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6'); + */ + print ''; + print ''; + + $i++; + } + + print ''.$langs->trans("Number").': '.$i.''; + print ''.$langs->trans("TotalHT").' : '.price($total_HT).''; + print ''.$langs->trans("TotalTTC").' : '.price($total_TTC).''; + print ' '; + print ''; + } + else + { + $this->error = $db->lasterror(); + return -1; + } + } + } + + /** + * recalculer + * TODO Replace this with call to update_price if not already done + * + * @param int $id Id of expense report + * @return int <0 if KO, >0 if OK + */ + public function recalculer($id) + { + $sql = 'SELECT tt.total_ht, tt.total_ttc, tt.total_tva'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as tt'; + $sql .= ' WHERE tt.'.$this->fk_element.' = '.$id; + + $total_ht = 0; $total_tva = 0; $total_ttc = 0; + + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num): + $objp = $this->db->fetch_object($result); + $total_ht += $objp->total_ht; + $total_tva += $objp->total_tva; + $i++; + endwhile; + + $total_ttc = $total_ht + $total_tva; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$total_ht; + $sql .= " , total_ttc = ".$total_ttc; + $sql .= " , total_tva = ".$total_tva; + $sql .= " WHERE rowid = ".$id; + $result = $this->db->query($sql); + if ($result): + $this->db->free($result); + return 1; + else: + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR); + return -3; + endif; + } + else + { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR); + return -3; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * fetch_lines + * + * @return int <0 if OK, >0 if KO + */ + public function fetch_lines() + { + // phpcs:enable + global $conf; + + $this->lines = array(); + + $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,'; + $sql .= ' de.'.$this->fk_element.', de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project, de.tva_tx, de.fk_ecm_files,'; + $sql .= ' de.total_ht, de.total_tva, de.total_ttc,'; + $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees,'; + $sql .= ' p.ref as ref_projet, p.title as title_projet'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid'; + $sql .= ' WHERE de.'.$this->fk_element.' = '.$this->id; + if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID)) + { + $sql .= ' ORDER BY de.rang ASC, de.rowid ASC'; + } + else + { + $sql .= ' ORDER BY de.rang ASC, de.date ASC'; + } + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $objp = $this->db->fetch_object($resql); + + $deplig = new ExpenseReportLine($this->db); + + $deplig->rowid = $objp->rowid; + $deplig->id = $objp->rowid; + $deplig->comments = $objp->comments; + $deplig->qty = $objp->qty; + $deplig->value_unit = $objp->value_unit; + $deplig->date = $objp->date; + $deplig->dates = $this->db->jdate($objp->date); + + $deplig->fk_expensereport = $objp->fk_expensereport; + $deplig->fk_c_type_fees = $objp->fk_c_type_fees; + $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; + $deplig->fk_projet = $objp->fk_project; // deprecated + $deplig->fk_project = $objp->fk_project; + $deplig->fk_ecm_files = $objp->fk_ecm_files; + + $deplig->total_ht = $objp->total_ht; + $deplig->total_tva = $objp->total_tva; + $deplig->total_ttc = $objp->total_ttc; + + $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees; + $deplig->type_fees_libelle = $objp->libelle_type_fees; + $deplig->tva_tx = $objp->tva_tx; + $deplig->vatrate = $objp->tva_tx; + $deplig->projet_ref = $objp->ref_projet; + $deplig->projet_title = $objp->title_projet; + + $deplig->rang = $objp->rang; + + $this->lines[$i] = $deplig; + + $i++; + } + $this->db->free($resql); + return 1; + } + else + { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR); + return -3; + } + } + + + /** + * delete + * + * @param User $fuser User that delete + * @return int <0 if KO, >0 if OK + */ + public function delete(User $fuser = null) + { + global $user, $langs, $conf; + + if (!$rowid) $rowid = $this->id; + + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line.' WHERE '.$this->fk_element.' = '.$rowid; + if ($this->db->query($sql)) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid = '.$rowid; + $resql = $this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return 1; + } + else + { + $this->error = $this->db->error()." sql=".$sql; + dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); + $this->db->rollback(); + return -6; + } + } + else + { + $this->error = $this->db->error()." sql=".$sql; + dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); + $this->db->rollback(); + return -4; + } + } + + /** + * Set to status validate + * + * @param User $fuser User @@ -1261,5 +1139,5 @@ - * @return int Return integer <0 if KO, 0 if nothing done, >0 if OK - */ - public function setValidate($fuser, $notrigger = 0) - { - global $conf, $langs, $user; + * @return int <0 if KO, 0 if nothing done, >0 if OK + */ + public function setValidate($fuser, $notrigger = 0) + { + global $conf, $langs, $user; @@ -1270,7 +1148,8 @@ - // Protection - if ($this->status == self::STATUS_VALIDATED) { - dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); - return 0; - } - - $this->date_valid = $now; // Required for the getNextNum later. + // Protection + if ($this->statut == self::STATUS_VALIDATED) + { + dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); + return 0; + } + + $this->date_valid = $now; // Required for the getNextNum later. @@ -1279,10 +1158,11 @@ - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life - $num = $this->getNextNumRef(); - } else { - $num = $this->ref; - } - if (empty($num) || $num < 0) { - return -1; - } - - $this->newref = dol_sanitizeFileName($num); + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life + { + $num = $this->getNextNumRef(); + } + else + { + $num = $this->ref; + } + if (empty($num) || $num < 0) return -1; + + $this->newref = dol_sanitizeFileName($num); @@ -1292,11 +1172,13 @@ - // Validate - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET ref = '".$this->db->escape($num)."',"; - $sql .= " fk_statut = ".self::STATUS_VALIDATED.","; - $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',"; - $sql .= " fk_user_valid = ".((int) $user->id); - $sql .= " WHERE rowid = ".((int) $this->id); - - $resql = $this->db->query($sql); - if ($resql) { - if (!$error && !$notrigger) { + // Validate + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$num."',"; + $sql .= " fk_statut = ".self::STATUS_VALIDATED.","; + $sql .= " date_valid='".$this->db->idate($this->date_valid)."',"; + $sql .= " fk_user_valid = ".$user->id; + $sql .= " WHERE rowid = ".$this->id; + + $resql = $this->db->query($sql); + if ($resql) + { + if (!$error && !$notrigger) + { @@ -1311,10 +1193,12 @@ - if (!$error) { - $this->oldref = $this->ref; - - // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - // Now we rename also files into index - $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)."'"; - $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' AND entity = ".((int) $this->entity); + if (!$error) + { + $this->oldref = $this->ref; + + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + // Now we rename also files into index + $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)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; @@ -1322,13 +1206,3 @@ - if (!$resql) { - $error++; - $this->error = $this->db->lasterror(); - } - $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'expensereport/".$this->db->escape($this->newref)."'"; - $sql .= " WHERE filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; - $resql = $this->db->query($sql); - if (!$resql) { - $error++; - $this->error = $this->db->lasterror(); - } - - // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments + if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + + // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments @@ -1337,17 +1211,20 @@ - $dirsource = $conf->expensereport->multidir_output[$this->entity].'/'.$oldref; - $dirdest = $conf->expensereport->multidir_output[$this->entity].'/'.$newref; - if (!$error && file_exists($dirsource)) { - dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest); - - if (@rename($dirsource, $dirdest)) { - dol_syslog("Rename ok"); - // Rename docs starting with $oldref with $newref - $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) { - $dirsource = $fileentry['name']; - $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource = $fileentry['path'].'/'.$dirsource; - $dirdest = $fileentry['path'].'/'.$dirdest; - @rename($dirsource, $dirdest); - } - } + $dirsource = $conf->expensereport->dir_output.'/'.$oldref; + $dirdest = $conf->expensereport->dir_output.'/'.$newref; + if (!$error && file_exists($dirsource)) + { + dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest); + + if (@rename($dirsource, $dirdest)) + { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->expensereport->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) + { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } @@ -1359,3 +1236,4 @@ - if (!$error) { - $this->ref = $num; - $this->status = self::STATUS_VALIDATED; + if (!$error) + { + $this->ref = $num; + $this->statut = self::STATUS_VALIDATED; @@ -1364 +1242,2 @@ - if (empty($error)) { + if (empty($error)) + { @@ -1367 +1246,3 @@ - } else { + } + else + { @@ -1372 +1253,3 @@ - } else { + } + else + { @@ -1374,50 +1257,56 @@ - $this->error = $this->db->lasterror(); - return -1; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * set_save_from_refuse - * - * @param User $fuser User - * @return int Return integer <0 if KO, >0 if OK - */ - public function set_save_from_refuse($fuser) - { - // phpcs:enable - // Sélection de la date de début de la NDF - $sql = 'SELECT date_debut'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " WHERE rowid = ".((int) $this->id); - - $result = $this->db->query($sql); - - $objp = $this->db->fetch_object($result); - - $this->date_debut = $this->db->jdate($objp->date_debut); - - if ($this->status != self::STATUS_VALIDATED) { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET fk_statut = ".self::STATUS_VALIDATED; - $sql .= " WHERE rowid = ".((int) $this->id); - - dol_syslog(get_class($this)."::set_save_from_refuse", LOG_DEBUG); - - if ($this->db->query($sql)) { - return 1; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } else { - dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING); - } - - return 0; - } - - /** - * Set status to approved - * - * @param User $fuser User + $this->error = $this->db->lasterror(); + return -1; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * set_save_from_refuse + * + * @param User $fuser User + * @return int <0 if KO, >0 if OK + */ + public function set_save_from_refuse($fuser) + { + // phpcs:enable + global $conf, $langs; + + // Sélection de la date de début de la NDF + $sql = 'SELECT date_debut'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' WHERE rowid = '.$this->id; + + $result = $this->db->query($sql); + + $objp = $this->db->fetch_object($result); + + $this->date_debut = $this->db->jdate($objp->date_debut); + + if ($this->fk_statut != self::STATUS_VALIDATED) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET fk_statut = ".self::STATUS_VALIDATED; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::set_save_from_refuse sql=".$sql, LOG_DEBUG); + + if ($this->db->query($sql)) + { + return 1; + } + else + { + $this->error = $this->db->lasterror(); + return -1; + } + } + else + { + dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING); + } + } + + /** + * Set status to approved + * + * @param User $fuser User @@ -1425,10 +1314,11 @@ - * @return int Return integer <0 if KO, 0 if nothing done, >0 if OK - */ - public function setApproved($fuser, $notrigger = 0) - { - $now = dol_now(); - $error = 0; - - // date approval - $this->date_approve = $now; - if ($this->status != self::STATUS_APPROVED) { + * @return int <0 if KO, 0 if nothing done, >0 if OK + */ + public function setApproved($fuser, $notrigger = 0) + { + $now = dol_now(); + $error = 0; + + // date approval + $this->date_approve = $now; + if ($this->fk_statut != self::STATUS_APPROVED) + { @@ -1437,6 +1327,8 @@ - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".((int) $fuser->id).","; - $sql .= " date_approve='".$this->db->idate($this->date_approve)."'"; - $sql .= " WHERE rowid = ".((int) $this->id); - if ($this->db->query($sql)) { - if (!$notrigger) { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".$fuser->id.","; + $sql .= " date_approve='".$this->db->idate($this->date_approve)."'"; + $sql .= ' WHERE rowid = '.$this->id; + if ($this->db->query($sql)) + { + if (!$notrigger) + { @@ -1452 +1344,2 @@ - if (empty($error)) { + if (empty($error)) + { @@ -1455 +1348,3 @@ - } else { + } + else + { @@ -1460 +1355,3 @@ - } else { + } + else + { @@ -1462,21 +1359,23 @@ - $this->error = $this->db->lasterror(); - return -1; - } - } else { - dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING); - } - - return 0; - } - - /** - * setDeny - * - * @param User $fuser User - * @param string $details Details - * @param int $notrigger Disable triggers - * @return int - */ - public function setDeny($fuser, $details, $notrigger = 0) - { - $now = dol_now(); + $this->error = $this->db->lasterror(); + return -1; + } + } + else + { + dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING); + } + + return 0; + } + + /** + * setDeny + * + * @param User $fuser User + * @param string $details Details + * @param int $notrigger Disable triggers + * @return int + */ + public function setDeny($fuser, $details, $notrigger = 0) + { + $now = dol_now(); @@ -1485,16 +1384,18 @@ - // date de refus - if ($this->status != self::STATUS_REFUSED) { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".((int) $fuser->id).","; - $sql .= " date_refuse='".$this->db->idate($now)."',"; - $sql .= " detail_refuse='".$this->db->escape($details)."',"; - $sql .= " fk_user_approve = NULL"; - $sql .= " WHERE rowid = ".((int) $this->id); - if ($this->db->query($sql)) { - $this->fk_statut = 99; // deprecated - $this->status = 99; - $this->fk_user_refuse = $fuser->id; - $this->detail_refuse = $details; - $this->date_refuse = $now; - - if (!$notrigger) { + // date de refus + if ($this->fk_statut != self::STATUS_REFUSED) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".$fuser->id.","; + $sql .= " date_refuse='".$this->db->idate($now)."',"; + $sql .= " detail_refuse='".$this->db->escape($details)."',"; + $sql .= " fk_user_approve = NULL"; + $sql .= ' WHERE rowid = '.$this->id; + if ($this->db->query($sql)) + { + $this->fk_statut = 99; + $this->fk_user_refuse = $fuser->id; + $this->detail_refuse = $details; + $this->date_refuse = $now; + + if (!$notrigger) + { @@ -1510 +1411,2 @@ - if (empty($error)) { + if (empty($error)) + { @@ -1513 +1415,3 @@ - } else { + } + else + { @@ -1518 +1422,3 @@ - } else { + } + else + { @@ -1520,17 +1426,15 @@ - $this->error = $this->db->lasterror(); - return -1; - } - } else { - dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING); - } - - return 0; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * set_unpaid - * - * @deprecated - * @see setUnpaid() - * @param User $fuser User + $this->error = $this->db->lasterror(); + return -1; + } + } + else + { + dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING); + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * set_unpaid + * + * @param User $fuser User @@ -1538,18 +1442,5 @@ - * @return int Return integer <0 if KO, >0 if OK - */ - public function set_unpaid($fuser, $notrigger = 0) - { - // phpcs:enable - dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE); - return $this->setUnpaid($fuser, $notrigger); - } - - /** - * set_unpaid - * - * @param User $fuser User - * @param int $notrigger Disable triggers - * @return int Return integer <0 if KO, >0 if OK - */ - public function setUnpaid($fuser, $notrigger = 0) - { + * @return int <0 if KO, >0 if OK + */ + public function set_unpaid($fuser, $notrigger = 0) + { + // phpcs:enable @@ -1558 +1449,2 @@ - if ($this->paid) { + if ($this->paid) + { @@ -1561,8 +1453,10 @@ - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED; - $sql .= " WHERE rowid = ".((int) $this->id); - - dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG); - - if ($this->db->query($sql)) { - if (!$notrigger) { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG); + + if ($this->db->query($sql)) + { + if (!$notrigger) + { @@ -1578 +1472,2 @@ - if (empty($error)) { + if (empty($error)) + { @@ -1581 +1476,3 @@ - } else { + } + else + { @@ -1586 +1483,3 @@ - } else { + } + else + { @@ -1591,13 +1490,13 @@ - } else { - dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING); - } - - return 0; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * set_cancel - * - * @param User $fuser User - * @param string $detail Detail + } + else + { + dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING); + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * set_cancel + * + * @param User $fuser User + * @param string $detail Detail @@ -1605,5 +1504,5 @@ - * @return int Return integer <0 if KO, >0 if OK - */ - public function set_cancel($fuser, $detail, $notrigger = 0) - { - // phpcs:enable + * @return int <0 if KO, >0 if OK + */ + public function set_cancel($fuser, $detail, $notrigger = 0) + { + // phpcs:enable @@ -1611,2 +1510,3 @@ - $this->date_cancel = $this->db->idate(dol_now()); - if ($this->status != self::STATUS_CANCELED) { + $this->date_cancel = $this->db->idate(dol_now()); + if ($this->fk_statut != self::STATUS_CANCELED) + { @@ -1615,10 +1515,12 @@ - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".((int) $fuser->id); - $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'"; - $sql .= ", detail_cancel='".$this->db->escape($detail)."'"; - $sql .= " WHERE rowid = ".((int) $this->id); - - dol_syslog(get_class($this)."::set_cancel", LOG_DEBUG); - - if ($this->db->query($sql)) { - if (!$notrigger) { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".$fuser->id; + $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'"; + $sql .= " ,detail_cancel='".$this->db->escape($detail)."'"; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG); + + if ($this->db->query($sql)) + { + if (!$notrigger) + { @@ -1634 +1536,2 @@ - if (empty($error)) { + if (empty($error)) + { @@ -1637 +1540,3 @@ - } else { + } + else + { @@ -1642 +1547,3 @@ - } else { + } + else + { @@ -1644,23 +1551,25 @@ - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING); - } - return 0; - } - - /** - * Return next reference of expense report not already used - * - * @return string free ref - */ - public function getNextNumRef() - { - global $langs, $conf; - $langs->load("trips"); - - if (getDolGlobalString('EXPENSEREPORT_ADDON')) { - $mybool = false; - - $file = getDolGlobalString('EXPENSEREPORT_ADDON') . ".php"; + $this->error = $this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING); + } + } + + /** + * Return next reference of expense report not already used + * + * @return string free ref + */ + public function getNextNumRef() + { + global $langs, $conf; + $langs->load("trips"); + + if (!empty($conf->global->EXPENSEREPORT_ADDON)) + { + $mybool = false; + + $file = $conf->global->EXPENSEREPORT_ADDON.".php"; @@ -1671,18 +1580,22 @@ - foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/expensereport/"); - - // Load file with numbering class (if found) - $mybool |= @include_once $dir.$file; - } - - if ($mybool === false) { - dol_print_error('', "Failed to include file ".$file); - return ''; - } - - $obj = new $classname(); - $numref = $obj->getNextValue($this); - - if ($numref != "") { - return $numref; - } else { + foreach ($dirmodels as $reldir) + { + $dir = dol_buildpath($reldir."core/modules/expensereport/"); + + // Load file with numbering class (if found) + $mybool |= @include_once $dir.$file; + } + + if ($mybool === false) { + dol_print_error('', "Failed to include file ".$file); + return ''; + } + + $obj = new $classname(); + $numref = $obj->getNextValue($this); + + if ($numref != "") + { + return $numref; + } + else + { @@ -1691,8 +1604,137 @@ - //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); - return -1; - } - } else { - $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined"; - return -2; - } - } + //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); + return -1; + } + } + else + { + $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined"; + return -2; + } + } + + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $max Max length of shown ref + * @param int $short 1=Return just URL + * @param string $moretitle Add more text to title tooltip + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1) + { + global $langs, $conf; + + $result = ''; + + $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id; + + if ($short) return $url; + + $label = ''.$langs->trans("ShowExpenseReport").''; + if (!empty($this->ref)) + $label .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->total_ht)) + $label .= '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_tva)) + $label .= '
'.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_ttc)) + $label .= '
'.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + if ($moretitle) $label .= ' - '.$moretitle; + + //if ($option != 'nolink') + //{ + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; + if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + //} + + $ref = $this->ref; + if (empty($ref)) $ref = $this->id; + + $linkclose = ''; + if (empty($notooltip)) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("ShowExpenseReport"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; + } + + $linkstart = ''; + $linkend = ''; + + $result .= $linkstart; + if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= ($max ?dol_trunc($ref, $max) : $ref); + $result .= $linkend; + + return $result; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update total of an expense report when you add a line. + * + * @param string $ligne_total_ht Amount without taxes + * @param string $ligne_total_tva Amount of all taxes + * @return void + */ + public function update_totaux_add($ligne_total_ht, $ligne_total_tva) + { + // phpcs:enable + $this->total_ht = $this->total_ht + $ligne_total_ht; + $this->total_tva = $this->total_tva + $ligne_total_tva; + $this->total_ttc = $this->total_ht + $this->total_tva; + + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$this->total_ht; + $sql .= " , total_ttc = ".$this->total_ttc; + $sql .= " , total_tva = ".$this->total_tva; + $sql .= " WHERE rowid = ".$this->id; + + $result = $this->db->query($sql); + if ($result): + return 1; + else: + $this->error = $this->db->error(); + return -1; + endif; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update total of an expense report when you delete a line. + * + * @param string $ligne_total_ht Amount without taxes + * @param string $ligne_total_tva Amount of all taxes + * @return void + */ + public function update_totaux_del($ligne_total_ht, $ligne_total_tva) + { + // phpcs:enable + $this->total_ht = $this->total_ht - $ligne_total_ht; + $this->total_tva = $this->total_tva - $ligne_total_tva; + $this->total_ttc = $this->total_ht + $this->total_tva; + + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$this->total_ht; + $sql .= " , total_ttc = ".$this->total_ttc; + $sql .= " , total_tva = ".$this->total_tva; + $sql .= " WHERE rowid = ".$this->id; + + $result = $this->db->query($sql); + if ($result): + return 1; + else: + $this->error = $this->db->error(); + return -1; + endif; + } @@ -1701,163 +1743 @@ - * getTooltipContentArray - * - * @param array $params ex option, infologin - * @since v18 - * @return array - */ - public function getTooltipContentArray($params) - { - global $conf, $langs; - - $langs->load('expensereport'); - - $nofetch = !empty($params['nofetch']); - $moretitle = $params['moretitle'] ?? ''; - - $datas = array(); - $datas['picto'] = img_picto('', $this->picto).' '.$langs->trans("ExpenseReport").''; - if (isset($this->status)) { - $datas['picto'] .= ' '.$this->getLibStatut(5); - } - if ($moretitle) { - $datas['picto'] .= ' - '.$moretitle; - } - if (!empty($this->ref)) { - $datas['ref'] = '
'.$langs->trans('Ref').': '.$this->ref; - } - if (!empty($this->total_ht)) { - $datas['total_ht'] = '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - } - if (!empty($this->total_tva)) { - $datas['total_tva'] = '
'.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - } - if (!empty($this->total_ttc)) { - $datas['total_ttc'] = '
'.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - } - - return $datas; - } - - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param string $option Where point the link ('', 'document', ..) - * @param int $max Max length of shown ref - * @param int $short 1=Return just URL - * @param string $moretitle Add more text to title tooltip - * @param int $notooltip 1=Disable tooltip - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string String with URL - */ - public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1) - { - global $langs, $conf, $hookmanager; - - $result = ''; - - $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id; - - if ($short) { - return $url; - } - - $params = [ - 'id' => $this->id, - 'objecttype' => $this->element, - 'option' => $option, - 'moretitle' => $moretitle, - 'nofetch' => 1, - ]; - $classfortooltip = 'classfortooltip'; - $dataparams = ''; - if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) { - $classfortooltip = 'classforajaxtooltip'; - $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"'; - $label = ''; - } else { - $label = implode($this->getTooltipContentArray($params)); - } - - if ($option != 'nolink') { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { - $add_save_lastsearch_values = 1; - } - if ($add_save_lastsearch_values) { - $url .= '&save_lastsearch_values=1'; - } - } - - $ref = $this->ref; - if (empty($ref)) { - $ref = $this->id; - } - - $linkclose = ''; - if (empty($notooltip)) { - if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) { - $label = $langs->trans("ShowExpenseReport"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"'); - $linkclose .= $dataparams.' class="'.$classfortooltip.'"'; - } - - $linkstart = ''; - $linkend = ''; - - $result .= $linkstart; - if ($withpicto) { - $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1); - } - if ($withpicto != 2) { - $result .= ($max ? dol_trunc($ref, $max) : $ref); - } - $result .= $linkend; - - global $action; - $hookmanager->initHooks(array($this->element . 'dao')); - $parameters = array('id'=>$this->id, 'getnomurl' => &$result); - $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) { - $result = $hookmanager->resPrint; - } else { - $result .= $hookmanager->resPrint; - } - return $result; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Update total of an expense report when you add a line. - * - * @param string $ligne_total_ht Amount without taxes - * @param string $ligne_total_tva Amount of all taxes - * @return int - */ - public function update_totaux_add($ligne_total_ht, $ligne_total_tva) - { - // phpcs:enable - $this->total_ht = $this->total_ht + $ligne_total_ht; - $this->total_tva = $this->total_tva + $ligne_total_tva; - $this->total_ttc = $this->total_ht + $this->total_tva; - - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " total_ht = ".$this->total_ht; - $sql .= " , total_ttc = ".$this->total_ttc; - $sql .= " , total_tva = ".$this->total_tva; - $sql .= " WHERE rowid = ".((int) $this->id); - - $result = $this->db->query($sql); - if ($result) { - return 1; - } else { - $this->error = $this->db->error(); - return -1; - } - } - - /** - * Add expense report line + * addline @@ -1866 +1746 @@ - * @param double $up Unit price (price with tax) + * @param double $up Value init @@ -1875 +1755 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -1877 +1757 @@ - 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) + 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) @@ -1881,21 +1761,10 @@ - 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); - - if ($this->status == self::STATUS_DRAFT) { - if (empty($qty)) { - $qty = 0; - } - if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) { - $fk_c_type_fees = 0; - } - if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) { - $fk_c_exp_tax_cat = 0; - } - if (empty($vatrate) || $vatrate < 0) { - $vatrate = 0; - } - if (empty($date)) { - $date = ''; - } - if (empty($fk_project)) { - $fk_project = 0; - } + 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); + + if ($this->fk_statut == self::STATUS_DRAFT) + { + if (empty($qty)) $qty = 0; + if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) $fk_c_type_fees = 0; + if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) $fk_c_exp_tax_cat = 0; + if (empty($vatrate) || $vatrate < 0) $vatrate = 0; + if (empty($date)) $date = ''; + if (empty($fk_project)) $fk_project = 0; @@ -1913,6 +1782 @@ - // We don't know seller and buyer for expense reports - $seller = $mysoc; // We use same than current company (expense report are often done in same country) - $seller->tva_assuj = 1; // Most seller uses vat - $buyer = new Societe($this->db); - - $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller); + $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty); @@ -1921,2 +1785,2 @@ - $reg = array(); - if (preg_match('/\s*\((.*)\)/', $vatrate, $reg)) { + if (preg_match('/\s*\((.*)\)/', $vatrate, $reg)) + { @@ -1928 +1792,3 @@ - $tmp = calcul_price_total($qty, $up, 0, $vatrate, -1, -1, 0, 'TTC', 0, $type, $seller, $localtaxes_type); + $seller = ''; // seller is unknown + + $tmp = calcul_price_total($qty, $up, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type); @@ -1931 +1796,0 @@ - @@ -1934,5 +1798,0 @@ - $this->line->localtax1_tx = $localtaxes_type[1]; - $this->line->localtax2_tx = $localtaxes_type[3]; - $this->line->localtax1_type = $localtaxes_type[0]; - $this->line->localtax2_type = $localtaxes_type[2]; - @@ -1942,2 +1801,0 @@ - $this->line->total_localtax1 = $tmp[9]; - $this->line->total_localtax2 = $tmp[10]; @@ -1960,17 +1818,25 @@ - if ($result > 0) { - $result = $this->update_price(1); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. - if ($result > 0) { - $this->db->commit(); - return $this->line->id; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->error = $this->line->error; - dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } else { - dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR); + if ($result > 0) + { + $result = $this->update_price(); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. + if ($result > 0) + { + $this->db->commit(); + return $this->line->id; + } + else + { + $this->db->rollback(); + return -1; + } + } + else + { + $this->error = $this->line->error; + dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } + else + { + dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR); @@ -1978,2 +1844,2 @@ - return -3; - } + return -3; + } @@ -1985,3 +1851,3 @@ - * @param int $type Type of line - * @param string $seller Seller, but actually he is unknown - * @return boolean true or false + * @param int $type type of line + * @param string $seller seller, but actually he is unknown + * @return true or false @@ -1991 +1857 @@ - global $user, $conf, $db, $langs, $mysoc; + global $user, $conf, $db, $langs; @@ -1995,8 +1861,3 @@ - // We don't know seller and buyer for expense reports - if (!is_object($seller)) { - $seller = $mysoc; // We use same than current company (expense report are often done in same country) - $seller->tva_assuj = 1; // Most seller uses vat - } - - $expensereportrule = new ExpenseReportRule($db); - $rulestocheck = $expensereportrule->getAllRule($this->line->fk_c_type_fees, $this->line->date, $this->fk_user_author); + if (empty($conf->global->MAIN_USE_EXPENSE_RULE)) return true; // if don't use rules + + $rulestocheck = ExpenseReportRule::getAllRule($this->line->fk_c_type_fees, $this->line->date, $this->fk_user_author); @@ -2011,6 +1872,4 @@ - foreach ($rulestocheck as $rule) { - if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) { - $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type); - } else { - $amount_to_test = $current_total_ttc; // EX_EXP - } + foreach ($rulestocheck as $rule) + { + if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type); + else $amount_to_test = $current_total_ttc; // EX_EXP @@ -2020 +1879,2 @@ - if ($amount_to_test > $rule->amount) { + if ($amount_to_test > $rule->amount) + { @@ -2023 +1883,2 @@ - if ($rule->restrictive) { + if ($rule->restrictive) + { @@ -2028,2 +1889,4 @@ - $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)); - } else { + $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), $langs->trans('by'.$rule->code_expense_rules_type, price($new_current_total_ttc, 0, $langs, 1, -1, -1, $conf->currency))); + } + else + { @@ -2033 +1896 @@ - $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)); + $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), $langs->trans('nolimitby'.$rule->code_expense_rules_type)); @@ -2042 +1905,2 @@ - if ($violation > 0) { + if ($violation > 0) + { @@ -2049,2 +1912,0 @@ - $this->line->total_localtax1 = $tmp[9]; - $this->line->total_localtax2 = $tmp[10]; @@ -2053,2 +1914,0 @@ - } else { - return true; @@ -2055,0 +1916 @@ + else return true; @@ -2061,3 +1922 @@ - * @param int $type Type of line - * @param string $seller Seller, but actually he is unknown - * @return boolean True=applied, False=not applied + * @return boolean true=applied, false=not applied @@ -2065 +1924 @@ - public function applyOffset($type = 0, $seller = '') + public function applyOffset() @@ -2067,5 +1926,3 @@ - global $conf, $mysoc; - - if (!getDolGlobalString('MAIN_USE_EXPENSE_IK')) { - return false; - } + global $conf; + + if (empty($conf->global->MAIN_USE_EXPENSE_IK)) return false; @@ -2074 +1931,2 @@ - if ($userauthor->fetch($this->fk_user_author) <= 0) { + if ($userauthor->fetch($this->fk_user_author) <= 0) + { @@ -2080,10 +1938,4 @@ - // We don't know seller and buyer for expense reports - if (!is_object($seller)) { - $seller = $mysoc; // We use same than current company (expense report are often done in same country) - $seller->tva_assuj = 1; // Most seller uses vat - } - - $expenseik = new ExpenseReportIk($this->db); - $range = $expenseik->getRangeByUser($userauthor, $this->line->fk_c_exp_tax_cat); - - if (empty($range)) { + $range = ExpenseReportIk::getRangeByUser($userauthor, $this->line->fk_c_exp_tax_cat); + + if (empty($range)) + { @@ -2095,5 +1947,2 @@ - if (getDolGlobalString('MAIN_EXPENSE_APPLY_ENTIRE_OFFSET')) { - $ikoffset = $range->ikoffset; - } else { - $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year - } + if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) $ikoffset = $range->ikoffset; + else $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year @@ -2102 +1951,2 @@ - if (!$this->offsetAlreadyGiven()) { + if (!$this->offsetAlreadyGiven()) + { @@ -2110,2 +1959,0 @@ - $this->line->total_localtax1 = $tmp[9]; - $this->line->total_localtax2 = $tmp[10]; @@ -2127,6 +1975,12 @@ - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."expensereport_det d ON (e.rowid = d.fk_expensereport)"; - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_type_fees f ON (d.fk_c_type_fees = f.id AND f.code = 'EX_KME')"; - $sql .= " WHERE e.fk_user_author = ".(int) $this->fk_user_author; - $sql .= " AND YEAR(d.date) = '".dol_print_date($this->line->date, '%Y')."' AND MONTH(d.date) = '".dol_print_date($this->line->date, '%m')."'"; - if (!empty($this->line->id)) { - $sql .= ' AND d.rowid <> '.((int) $this->line->id); + $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'expensereport_det d ON (e.rowid = d.fk_expensereport)'; + $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_type_fees f ON (d.fk_c_type_fees = f.id AND f.code = "EX_KME")'; + $sql .= ' WHERE e.fk_user_author = '.(int) $this->fk_user_author; + $sql .= ' AND YEAR(d.date) = "'.dol_print_date($this->line->date, '%Y').'" AND MONTH(d.date) = "'.dol_print_date($this->line->date, '%m').'"'; + if (!empty($this->line->id)) $sql .= ' AND d.rowid <> '.$this->line->id; + + dol_syslog(get_class($this)."::offsetAlreadyGiven sql=".$sql); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num > 0) return true; @@ -2134,9 +1988,2 @@ - - dol_syslog(get_class($this)."::offsetAlreadyGiven"); - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - if ($num > 0) { - return true; - } - } else { + else + { @@ -2149,13 +1996,13 @@ - /** - * Update an expense report line. - * - * @param int $rowid Line to edit - * @param int $type_fees_id Type payment - * @param int $projet_id Project id - * @param double $vatrate Vat rate. Can be '8.5' or '8.5* (8.5NPROM...)' - * @param string $comments Description - * @param float $qty Qty - * @param double $value_unit Unit price (with taxes) - * @param int $date Date - * @param int $expensereport_id Expense report id - * @param int $fk_c_exp_tax_cat Id of category of car + /** + * Update an expense report line + * + * @param int $rowid Line to edit + * @param int $type_fees_id Type payment + * @param int $projet_id Project id + * @param double $vatrate Vat rate. Can be '8.5' or '8.5* (8.5NPROM...)' + * @param string $comments Description + * @param float $qty Qty + * @param double $value_unit Value init + * @param int $date Date + * @param int $expensereport_id Expense report id + * @param int $fk_c_exp_tax_cat Id of category of car @@ -2163,91 +2010,89 @@ - * @param int $notrigger 1=No trigger - * @return int Return integer <0 if KO, >0 if OK - */ - 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) - { - global $user, $mysoc; - - if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) { - $this->db->begin(); - - $error = 0; - $type = 0; // TODO What if type is service ? - - // We don't know seller and buyer for expense reports - $seller = $mysoc; // We use same than current company (expense report are often done in same country) - $seller->tva_assuj = 1; // Most seller uses vat - $seller->localtax1_assuj = $mysoc->localtax1_assuj; // We don't know, we reuse the state of company - $seller->localtax2_assuj = $mysoc->localtax1_assuj; // We don't know, we reuse the state of company - $buyer = new Societe($this->db); - - $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller); - - // Clean vat code - $reg = array(); - $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $vatrate, $reg)) { - $vat_src_code = $reg[1]; - $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. - } - $vatrate = preg_replace('/\*/', '', $vatrate); - - $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, -1, -1, 0, 'TTC', 0, $type, $seller, $localtaxes_type); - //var_dump($vatrate);var_dump($localtaxes_type);var_dump($tmp);exit; - // calcul total of line - //$total_ttc = price2num($qty*$value_unit, 'MT'); - - $tx_tva = $vatrate / 100; - $tx_tva = $tx_tva + 1; - - $this->line = new ExpenseReportLine($this->db); - $this->line->comments = $comments; - $this->line->qty = $qty; - $this->line->value_unit = $value_unit; - $this->line->date = $date; - - $this->line->fk_expensereport = $expensereport_id; - $this->line->fk_c_type_fees = $type_fees_id; - $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat; - $this->line->fk_projet = $projet_id; // deprecated - $this->line->fk_project = $projet_id; - - $this->line->vat_src_code = $vat_src_code; - $this->line->vatrate = price2num($vatrate); - $this->line->localtax1_tx = $localtaxes_type[1]; - $this->line->localtax2_tx = $localtaxes_type[3]; - $this->line->localtax1_type = $localtaxes_type[0]; - $this->line->localtax2_type = $localtaxes_type[2]; - - $this->line->total_ttc = $tmp[2]; - $this->line->total_ht = $tmp[0]; - $this->line->total_tva = $tmp[1]; - $this->line->total_localtax1 = $tmp[9]; - $this->line->total_localtax2 = $tmp[10]; - - $this->line->fk_ecm_files = $fk_ecm_files; - - $this->line->id = ((int) $rowid); - - // Select des infos sur le type fees - $sql = "SELECT c.code as code_type_fees, c.label as label_type_fees"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c"; - $sql .= " WHERE c.id = ".((int) $type_fees_id); - $resql = $this->db->query($sql); - if ($resql) { - $objp_fees = $this->db->fetch_object($resql); - $this->line->type_fees_code = $objp_fees->code_type_fees; - $this->line->type_fees_libelle = $objp_fees->label_type_fees; - $this->db->free($resql); - } - - // Select des informations du projet - $sql = "SELECT p.ref as ref_projet, p.title as title_projet"; - $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; - $sql .= " WHERE p.rowid = ".((int) $projet_id); - $resql = $this->db->query($sql); - if ($resql) { - $objp_projet = $this->db->fetch_object($resql); - $this->line->projet_ref = $objp_projet->ref_projet; - $this->line->projet_title = $objp_projet->title_projet; - $this->db->free($resql); - } + * @return int <0 if KO, >0 if OK + */ + 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) + { + global $user, $mysoc; + + if ($this->fk_statut == 0 || $this->fk_statut == 99) + { + $this->db->begin(); + + $type = 0; // TODO What if type is service ? + + // We don't know seller and buyer for expense reports + $seller = $mysoc; + $buyer = new Societe($this->db); + + $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller); + + // Clean vat code + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $vatrate, $reg)) + { + $vat_src_code = $reg[1]; + $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. + } + $vatrate = preg_replace('/\*/', '', $vatrate); + + $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type); + + // calcul total of line + //$total_ttc = price2num($qty*$value_unit, 'MT'); + + $tx_tva = $vatrate / 100; + $tx_tva = $tx_tva + 1; + $total_ht = price2num($total_ttc / $tx_tva, 'MT'); + + $total_tva = price2num($total_ttc - $total_ht, 'MT'); + // fin calculs + + $this->line = new ExpenseReportLine($this->db); + $this->line->comments = $comments; + $this->line->qty = $qty; + $this->line->value_unit = $value_unit; + $this->line->date = $date; + + $this->line->fk_expensereport = $expensereport_id; + $this->line->fk_c_type_fees = $type_fees_id; + $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat; + $this->line->fk_projet = $projet_id; // deprecated + $this->line->fk_project = $projet_id; + + $this->line->vat_src_code = $vat_src_code; + $this->line->vatrate = price2num($vatrate); + $this->line->total_ttc = $tmp[2]; + $this->line->total_ht = $tmp[0]; + $this->line->total_tva = $tmp[1]; + $this->line->localtax1_tx = $localtaxes_type[1]; + $this->line->localtax2_tx = $localtaxes_type[3]; + $this->line->localtax1_type = $localtaxes_type[0]; + $this->line->localtax2_type = $localtaxes_type[2]; + + $this->line->fk_ecm_files = $fk_ecm_files; + + $this->line->id = $rowid; + + // Select des infos sur le type fees + $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c"; + $sql .= " WHERE c.id = ".$type_fees_id; + $resql = $this->db->query($sql); + if ($resql) + { + $objp_fees = $this->db->fetch_object($resql); + $this->line->type_fees_code = $objp_fees->code_type_fees; + $this->line->type_fees_libelle = $objp_fees->libelle_type_fees; + $this->db->free($resql); + } + + // Select des informations du projet + $sql = "SELECT p.ref as ref_projet, p.title as title_projet"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql .= " WHERE p.rowid = ".$projet_id; + $resql = $this->db->query($sql); + if ($resql) { + $objp_projet = $this->db->fetch_object($resql); + $this->line->projet_ref = $objp_projet->ref_projet; + $this->line->projet_title = $objp_projet->title_projet; + $this->db->free($resql); + } @@ -2258,23 +2103,231 @@ - $result = $this->line->update($user); - if ($result < 0) { - $error++; - } - - if (!$error && !$notrigger) { - // Call triggers - $result = $this->call_trigger('EXPENSE_REPORT_DET_MODIFY', $user); - if ($result < 0) { - $error++; - } - // End call triggers - } - - if (!$error) { - $this->db->commit(); - return 1; - } else { - $this->error = $this->line->error; - $this->errors = $this->line->errors; - $this->db->rollback(); - return -2; - } + $result = $this->line->update($user); + if ($result > 0) + { + $this->db->commit(); + return 1; + } + else + { + $this->error = $this->line->error; + $this->errors = $this->line->errors; + $this->db->rollback(); + return -2; + } + } + } + + /** + * deleteline + * + * @param int $rowid Row id + * @param User $fuser User + * @return int <0 if KO, >0 if OK + */ + public function deleteline($rowid, $fuser = '') + { + $this->db->begin(); + + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE rowid = '.$rowid; + + dol_syslog(get_class($this)."::deleteline sql=".$sql); + $result = $this->db->query($sql); + if (!$result) + { + $this->error = $this->db->error(); + dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -1; + } + + $this->db->commit(); + + return 1; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * periode_existe + * + * @param User $fuser User + * @param integer $date_debut Start date + * @param integer $date_fin End date + * @return int <0 if KO, >0 if OK + */ + public function periode_existe($fuser, $date_debut, $date_fin) + { + // phpcs:enable + $sql = "SELECT rowid, date_debut, date_fin"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " WHERE fk_user_author = '{$fuser->id}'"; + + dol_syslog(get_class($this)."::periode_existe sql=".$sql); + $result = $this->db->query($sql); + if ($result) { + $num_rows = $this->db->num_rows($result); $i = 0; + + if ($num_rows > 0) + { + $date_d_form = $date_debut; + $date_f_form = $date_fin; + + $existe = false; + + while ($i < $num_rows) + { + $objp = $this->db->fetch_object($result); + + $date_d_req = $this->db->jdate($objp->date_debut); // 3 + $date_f_req = $this->db->jdate($objp->date_fin); // 4 + + if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) $existe = true; + + $i++; + } + + if ($existe) return 1; + else return 0; + } + else + { + return 0; + } + } + else + { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR); + return -1; + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of people with permission to validate expense reports. + * Search for permission "approve expense report" + * + * @return array Array of user ids + */ + public function fetch_users_approver_expensereport() + { + // phpcs:enable + $users_validator = array(); + + $sql = "SELECT DISTINCT ur.fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; + $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; + $sql .= "UNION"; + $sql .= " SELECT DISTINCT ugu.fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; + $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; + //print $sql; + + dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql); + $result = $this->db->query($sql); + if ($result) + { + $num_rows = $this->db->num_rows($result); $i = 0; + while ($i < $num_rows) + { + $objp = $this->db->fetch_object($result); + array_push($users_validator, $objp->fk_user); + $i++; + } + return $users_validator; + } + else + { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR); + return -1; + } + } + + /** + * Create a document onto disk accordign to template module. + * + * @param string $modele Force le mnodele a utiliser ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) + { + global $conf, $langs; + + $langs->load("trips"); + + if (!dol_strlen($modele)) { + $modele = 'standard'; + + if ($this->modelpdf) { + $modele = $this->modelpdf; + } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) { + $modele = $conf->global->EXPENSEREPORT_ADDON_PDF; + } + } + + $modelpath = "core/modules/expensereport/doc/"; + + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + } + + /** + * List of types + * + * @param int $active Active or not + * @return array + */ + public function listOfTypes($active = 1) + { + global $langs; + $ret = array(); + $sql = "SELECT id, code, label"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees"; + $sql .= " WHERE active = ".$active; + dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + $ret[$obj->code] = (($langs->trans($obj->code) != $obj->code) ? $langs->trans($obj->code) : $obj->label); + $i++; + } + } + else + { + dol_print_error($this->db); + } + return $ret; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Charge indicateurs this->nb pour le tableau de bord + * + * @return int <0 if KO, >0 if OK + */ + public function load_state_board() + { + // phpcs:enable + global $conf, $user; + + $this->nb = array(); + + $sql = "SELECT count(ex.rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; + $sql .= " WHERE ex.fk_statut > 0"; + $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; + if (empty($user->rights->expensereport->readall)) + { + $userchildids = $user->getAllChildIds(1); + $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")"; + $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))"; @@ -2283,24 +2336,43 @@ - return 0; - } - - /** - * deleteline - * - * @param int $rowid Row id - * @param User $fuser User - * @param int $notrigger 1=No trigger - * @return int Return integer <0 if KO, >0 if OK - */ - public function deleteline($rowid, $fuser = '', $notrigger = 0) - { - $error=0; - - $this->db->begin(); - - if (!$notrigger) { - // Call triggers - $result = $this->call_trigger('EXPENSE_REPORT_DET_DELETE', $fuser); - if ($result < 0) { - $error++; - } - // End call triggers + $resql = $this->db->query($sql); + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + $this->nb["expensereports"] = $obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error = $this->db->error(); + return -1; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Objet user + * @param string $option 'topay' or 'toapprove' + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + public function load_board($user, $option = 'topay') + { + // phpcs:enable + global $conf, $langs; + + if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe + + $now = dol_now(); + + $sql = "SELECT ex.rowid, ex.date_valid"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; + if ($option == 'toapprove') $sql .= " WHERE ex.fk_statut = 2"; + else $sql .= " WHERE ex.fk_statut = 5"; + $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; + if (empty($user->rights->expensereport->readall)) + { + $userchildids = $user->getAllChildIds(1); + $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")"; + $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))"; @@ -2309,340 +2381,106 @@ - $sql = ' DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql .= ' WHERE rowid = '.((int) $rowid); - - dol_syslog(get_class($this)."::deleteline sql=".$sql); - $result = $this->db->query($sql); - - if (!$result || $error > 0) { - $this->error = $this->db->error(); - dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -1; - } - - $this->update_price(1); - - $this->db->commit(); - - return 1; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * periode_existe - * - * @param User $fuser User - * @param integer $date_debut Start date - * @param integer $date_fin End date - * @return int Return integer <0 if KO, >0 if OK - */ - public function periode_existe($fuser, $date_debut, $date_fin) - { - global $conf; - - // phpcs:enable - $sql = "SELECT rowid, date_debut, date_fin"; - $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " WHERE entity = ".((int) $conf->entity); // not shared, only for the current entity - $sql .= " AND fk_user_author = ".((int) $fuser->id); - - dol_syslog(get_class($this)."::periode_existe sql=".$sql); - $result = $this->db->query($sql); - if ($result) { - $num_rows = $this->db->num_rows($result); - $i = 0; - - if ($num_rows > 0) { - $date_d_form = $date_debut; - $date_f_form = $date_fin; - - while ($i < $num_rows) { - $objp = $this->db->fetch_object($result); - - $date_d_req = $this->db->jdate($objp->date_debut); // 3 - $date_f_req = $this->db->jdate($objp->date_fin); // 4 - - if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) { - return $objp->rowid; - } - - $i++; - } - - return 0; - } else { - return 0; - } - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR); - return -1; - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of people with permission to validate expense reports. - * Search for permission "approve expense report" - * - * @return array|int Array of user ids, <0 if KO - */ - public function fetch_users_approver_expensereport() - { - // phpcs:enable - $users_validator = array(); - - $sql = "SELECT DISTINCT ur.fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; - $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; - $sql .= " UNION"; - $sql .= " SELECT DISTINCT ugu.fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; - $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; - //print $sql; - - dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql); - $result = $this->db->query($sql); - if ($result) { - $num_rows = $this->db->num_rows($result); - $i = 0; - while ($i < $num_rows) { - $objp = $this->db->fetch_object($result); - array_push($users_validator, $objp->fk_user); - $i++; - } - return $users_validator; - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR); - return -1; - } - } - - /** - * Create a document onto disk accordign to template module. - * - * @param string $modele Force le mnodele a utiliser ('' to not force) - * @param Translate $outputlangs objet lang a utiliser pour traduction - * @param int $hidedetails Hide details of lines - * @param int $hidedesc Hide description - * @param int $hideref Hide ref - * @param null|array $moreparams Array to provide more information - * @return int 0 if KO, 1 if OK - */ - public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) - { - global $conf; - - $outputlangs->load("trips"); - - if (!dol_strlen($modele)) { - if (!empty($this->model_pdf)) { - $modele = $this->model_pdf; - } elseif (getDolGlobalString('EXPENSEREPORT_ADDON_PDF')) { - $modele = $conf->global->EXPENSEREPORT_ADDON_PDF; - } - } - - if (!empty($modele)) { - $modelpath = "core/modules/expensereport/doc/"; - - return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); - } else { - return 0; - } - } - - /** - * List of types - * - * @param int $active Active or not - * @return array - */ - public function listOfTypes($active = 1) - { - global $langs; - $ret = array(); - $sql = "SELECT id, code, label"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees"; - $sql .= " WHERE active = ".((int) $active); - dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) { - $obj = $this->db->fetch_object($result); - $ret[$obj->code] = (($langs->transnoentitiesnoconv($obj->code) != $obj->code) ? $langs->transnoentitiesnoconv($obj->code) : $obj->label); - $i++; - } - } else { - dol_print_error($this->db); - } - return $ret; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Charge indicateurs this->nb pour le tableau de bord - * - * @return int Return integer <0 if KO, >0 if OK - */ - public function load_state_board() - { - // phpcs:enable - global $conf, $user; - - $this->nb = array(); - - $sql = "SELECT count(ex.rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; - $sql .= " WHERE ex.fk_statut > 0"; - $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; - if (!$user->hasRight('expensereport', 'readall')) { - $userchildids = $user->getAllChildIds(1); - $sql .= " AND (ex.fk_user_author IN (".$this->db->sanitize(join(',', $userchildids)).")"; - $sql .= " OR ex.fk_user_validator IN (".$this->db->sanitize(join(',', $userchildids))."))"; - } - - $resql = $this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { - $this->nb["expensereports"] = $obj->nb; - } - $this->db->free($resql); - return 1; - } else { - dol_print_error($this->db); - $this->error = $this->db->error(); - return -1; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Objet user - * @param string $option 'topay' or 'toapprove' - * @return WorkboardResponse|int Return integer <0 if KO, WorkboardResponse if OK - */ - public function load_board($user, $option = 'topay') - { - // phpcs:enable - global $conf, $langs; - - if ($user->socid) { - return -1; // protection pour eviter appel par utilisateur externe - } - - $now = dol_now(); - - $sql = "SELECT ex.rowid, ex.date_valid"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; - if ($option == 'toapprove') { - $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED; - } else { - $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED; - } - $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; - if (!$user->hasRight('expensereport', 'readall')) { - $userchildids = $user->getAllChildIds(1); - $sql .= " AND (ex.fk_user_author IN (".$this->db->sanitize(join(',', $userchildids)).")"; - $sql .= " OR ex.fk_user_validator IN (".$this->db->sanitize(join(',', $userchildids))."))"; - } - - $resql = $this->db->query($sql); - if ($resql) { - $langs->load("trips"); - - $response = new WorkboardResponse(); - if ($option == 'toapprove') { - $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24; - $response->label = $langs->trans("ExpenseReportsToApprove"); - $response->labelShort = $langs->trans("ToApprove"); - $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut='.self::STATUS_VALIDATED; - } else { - $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24; - $response->label = $langs->trans("ExpenseReportsToPay"); - $response->labelShort = $langs->trans("StatusToPay"); - $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut='.self::STATUS_APPROVED; - } - $response->img = img_object('', "trip"); - - while ($obj = $this->db->fetch_object($resql)) { - $response->nbtodo++; - - if ($option == 'toapprove') { - if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) { - $response->nbtodolate++; - } - } else { - if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) { - $response->nbtodolate++; - } - } - } - - return $response; - } else { - dol_print_error($this->db); - $this->error = $this->db->error(); - return -1; - } - } - - /** - * Return if an expense report is late or not - * - * @param string $option 'topay' or 'toapprove' - * @return boolean True if late, False if not late - */ - public function hasDelay($option) - { - global $conf; - - // Only valid expenses reports - if ($option == 'toapprove' && $this->status != 2) { - return false; - } - if ($option == 'topay' && $this->status != 5) { - return false; - } - - $now = dol_now(); - if ($option == 'toapprove') { - return (!empty($this->datevalid) ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay); - } else { - return (!empty($this->datevalid) ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay); - } - } - - /** - * Return if object was dispatched into bookkeeping - * - * @return int Return integer <0 if KO, 0=no, 1=yes - */ - public function getVentilExportCompta() - { - $alreadydispatched = 0; - - $type = 'expense_report'; - - $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); - $resql = $this->db->query($sql); - if ($resql) { - $obj = $this->db->fetch_object($resql); - if ($obj) { - $alreadydispatched = $obj->nb; - } - } else { - $this->error = $this->db->lasterror(); - return -1; - } - - if ($alreadydispatched) { - return 1; - } - return 0; - } + $resql = $this->db->query($sql); + if ($resql) + { + $langs->load("trips"); + + $response = new WorkboardResponse(); + if ($option == 'toapprove') + { + $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24; + $response->label = $langs->trans("ExpenseReportsToApprove"); + $response->labelShort = $langs->trans("ToApprove"); + $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=2'; + } + else + { + $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24; + $response->label = $langs->trans("ExpenseReportsToPay"); + $response->labelShort = $langs->trans("StatusToPay"); + $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=5'; + } + $response->img = img_object('', "trip"); + + while ($obj = $this->db->fetch_object($resql)) + { + $response->nbtodo++; + + if ($option == 'toapprove') + { + if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) { + $response->nbtodolate++; + } + } + else + { + if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) { + $response->nbtodolate++; + } + } + } + + return $response; + } + else + { + dol_print_error($this->db); + $this->error = $this->db->error(); + return -1; + } + } + + /** + * Return if an expense report is late or not + * + * @param string $option 'topay' or 'toapprove' + * @return boolean True if late, False if not late + */ + public function hasDelay($option) + { + global $conf; + + // Only valid expenses reports + if ($option == 'toapprove' && $this->status != 2) return false; + if ($option == 'topay' && $this->status != 5) return false; + + $now = dol_now(); + if ($option == 'toapprove') + { + return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay); + } + else + return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay); + } + + /** + * Return if an expensereport was dispatched into bookkeeping + * + * @return int <0 if KO, 0=no, 1=yes + */ + public function getVentilExportCompta() + { + $alreadydispatched = 0; + + $type = 'expense_report'; + + $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id; + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) + { + $alreadydispatched = $obj->nb; + } + } + else + { + $this->error = $this->db->lasterror(); + return -1; + } + + if ($alreadydispatched) + { + return 1; + } + return 0; + } @@ -2662 +2500 @@ - $sql .= " WHERE ".$field." = ".((int) $this->id); + $sql .= ' WHERE '.$field.' = '.$this->id; @@ -2666 +2504,2 @@ - if ($resql) { + if ($resql) + { @@ -2669,2 +2508,4 @@ - return (empty($obj->amount) ? 0 : $obj->amount); - } else { + return $obj->amount; + } + else + { @@ -2675,140 +2515,0 @@ - - /** - * \brief Compute the cost of the kilometers expense based on the number of kilometers and the vehicule category - * - * @param int $fk_cat Category of the vehicule used - * @param float $qty Number of kilometers - * @param float $tva VAT rate - * @return int Return integer <0 if KO, total ttc if OK - */ - public function computeTotalKm($fk_cat, $qty, $tva) - { - global $langs, $db, $conf; - - $cumulYearQty = 0; - $ranges = array(); - $coef = 0; - - - if ($fk_cat < 0) { - $this->error = $langs->trans('ErrorBadParameterCat'); - return -1; - } - - if ($qty <= 0) { - $this->error = $langs->trans('ErrorBadParameterQty'); - return -1; - } - - $currentUser = new User($db); - $currentUser->fetch($this->fk_user); - $currentUser->getrights('expensereport'); - //Clean - $qty = price2num($qty); - - $sql = " SELECT r.range_ik, t.ikoffset, t.coef"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_ik t"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_exp_tax_range r ON r.rowid = t.fk_range"; - $sql .= " WHERE t.fk_c_exp_tax_cat = ".(int) $fk_cat; - $sql .= " ORDER BY r.range_ik ASC"; - - dol_syslog("expenseReport::computeTotalkm sql=".$sql, LOG_DEBUG); - - $result = $this->db->query($sql); - - if ($result) { - if ($conf->global->EXPENSEREPORT_CALCULATE_MILEAGE_EXPENSE_COEFFICIENT_ON_CURRENT_YEAR) { - $arrayDate = dol_getdate(dol_now()); - $sql = " SELECT count(n.qty) as cumul FROM ".MAIN_DB_PREFIX."expensereport_det n"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expensereport e ON e.rowid = n.fk_expensereport"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_fees tf ON tf.id = n.fk_c_type_fees"; - $sql.= " WHERE e.fk_user_author = ".(int) $this->fk_user_author; - $sql.= " AND YEAR(n.date) = ".(int) $arrayDate['year']; - $sql.= " AND tf.code = 'EX_KME' "; - $sql.= " AND e.fk_statut = ".(int) ExpenseReport::STATUS_VALIDATED; - - $resql = $this->db->query($sql); - - if ($resql) { - $obj = $this->db->fetch_object($resql); - $cumulYearQty = $obj->cumul; - } - - $qty = $cumulYearQty + $qty; - } - - $num = $this->db->num_rows($result); - - if ($num) { - for ($i = 0; $i < $num; $i++) { - $obj = $this->db->fetch_object($result); - - $ranges[$i] = $obj; - } - - - for ($i = 0; $i < $num; $i++) { - if ($i < ($num - 1)) { - if ($qty > $ranges[$i]->range_ik && $qty < $ranges[$i+1]->range_ik) { - $coef = $ranges[$i]->coef; - $offset = $ranges[$i]->ikoffset; - } - } else { - if ($qty > $ranges[$i]->range_ik) { - $coef = $ranges[$i]->coef; - $offset = $ranges[$i]->ikoffset; - } - } - } - $total_ht = $coef; - return $total_ht; - } else { - $this->error = $langs->trans('TaxUndefinedForThisCategory'); - return 0; - } - } else { - $this->error = $this->db->error()." sql=".$sql; - - return -1; - } - } - - /** - * Return clicable link of object (with eventually picto) - * - * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link) - * @param array $arraydata Array of data - * @return string HTML Code for Kanban thumb. - */ - public function getKanbanView($option = '', $arraydata = null) - { - global $langs; - - $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']); - - $return = '
'; - $return .= '
'; - $return .= ''; - $return .= img_picto('', $this->picto); - $return .= ''; - $return .= '
'; - $return .= ''.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).''; - if ($selected >= 0) { - $return .= ''; - } - if (array_key_exists('userauthor', $arraydata)) { - $return .= '
'.$arraydata['userauthor']->getNomUrl(-1).''; - } - if (property_exists($this, 'date_debut') && property_exists($this, 'date_fin')) { - $return .= '
'.dol_print_date($this->date_debut, 'day').''; - $return .= ' '.$langs->trans("To").' '; - $return .= ''.dol_print_date($this->date_fin, 'day').''; - } - if (method_exists($this, 'getLibStatut')) { - $return .= '
'.$this->getLibStatut(3).'
'; - } - $return .= '
'; - $return .= '
'; - $return .= '
'; - return $return; - } @@ -2821 +2522 @@ -class ExpenseReportLine extends CommonObjectLine +class ExpenseReportLine @@ -2823,11 +2524,6 @@ - /** - * @var DoliDB Database handler. - */ - public $db; - - /** - * @var string Name of table without prefix where object is stored - */ - public $table_element = 'expensereport_det'; - - /** + /** + * @var DoliDB Database handler. + */ + public $db; + + /** @@ -2838 +2534 @@ - /** + /** @@ -2843,227 +2539,156 @@ - public $comments; - public $qty; - public $value_unit; - public $date; - - /** - * @var int|string - */ - public $dates; - - /** - * @var int ID - */ - public $fk_c_type_fees; - - /** - * @var int ID - */ - public $fk_c_exp_tax_cat; - - /** - * @var int ID - */ - public $fk_projet; - - /** - * @var int ID - */ - public $fk_expensereport; - - public $type_fees_code; - public $type_fees_libelle; - public $type_fees_accountancy_code; - - public $projet_ref; - public $projet_title; - public $rang; - - public $vatrate; - public $vat_src_code; - public $tva_tx; - public $localtax1_tx; - public $localtax2_tx; - public $localtax1_type; - public $localtax2_type; - - public $total_ht; - public $total_tva; - public $total_ttc; - public $total_localtax1; - public $total_localtax2; - - // Multicurrency - /** - * @var int Currency ID - */ - public $fk_multicurrency; - - /** - * @var string multicurrency code - */ - public $multicurrency_code; - public $multicurrency_tx; - public $multicurrency_total_ht; - public $multicurrency_total_tva; - public $multicurrency_total_ttc; - - /** - * @var int ID into llx_ecm_files table to link line to attached file - */ - public $fk_ecm_files; - - public $rule_warning_message; - - - /** - * Constructor - * - * @param DoliDB $db Handlet database - */ - public function __construct($db) - { - $this->db = $db; - } - - /** - * Fetch record for expense report detailed line - * - * @param int $rowid Id of object to load - * @return int Return integer <0 if KO, >0 if OK - */ - public function fetch($rowid) - { - $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,'; - $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,'; - $sql .= ' fde.localtax1_tx, fde.localtax2_tx, fde.localtax1_type, fde.localtax2_type, fde.total_localtax1, fde.total_localtax2, fde.rule_warning_message,'; - $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,'; - $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde'; - $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. - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid'; - $sql .= ' WHERE fde.rowid = '.((int) $rowid); - - $result = $this->db->query($sql); - - if ($result) { - $objp = $this->db->fetch_object($result); - - $this->rowid = $objp->rowid; - $this->id = $objp->rowid; - $this->ref = $objp->ref; - $this->fk_expensereport = $objp->fk_expensereport; - $this->comments = $objp->comments; - $this->qty = $objp->qty; - $this->date = $objp->date; - $this->dates = $this->db->jdate($objp->date); - $this->value_unit = $objp->value_unit; - $this->fk_c_type_fees = $objp->fk_c_type_fees; - $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; - $this->fk_projet = $objp->fk_project; // deprecated - $this->fk_project = $objp->fk_project; - $this->type_fees_code = $objp->type_fees_code; - $this->type_fees_libelle = $objp->type_fees_libelle; - $this->projet_ref = $objp->projet_ref; - $this->projet_title = $objp->projet_title; - - $this->vatrate = $objp->vatrate; - $this->vat_src_code = $objp->vat_src_code; - $this->localtax1_tx = $objp->localtax1_tx; - $this->localtax2_tx = $objp->localtax2_tx; - $this->localtax1_type = $objp->localtax1_type; - $this->localtax2_type = $objp->localtax2_type; - - $this->total_ht = $objp->total_ht; - $this->total_tva = $objp->total_tva; - $this->total_ttc = $objp->total_ttc; - $this->total_localtax1 = $objp->total_localtax1; - $this->total_localtax2 = $objp->total_localtax2; - - $this->fk_ecm_files = $objp->fk_ecm_files; - - $this->rule_warning_message = $objp->rule_warning_message; - - $this->db->free($result); - - return $this->id; - } else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Insert a line of expense report - * - * @param int $notrigger 1=No trigger - * @param bool $fromaddline false=keep default behavior, true=exclude the update_price() of parent object - * @return int Return integer <0 if KO, >0 if OK - */ - public function insert($notrigger = 0, $fromaddline = false) - { - global $user, $conf; - - $error = 0; - - dol_syslog("ExpenseReportLine::Insert", LOG_DEBUG); - - // Clean parameters - $this->comments = trim($this->comments); - if (empty($this->value_unit)) { - $this->value_unit = 0; - } - $this->qty = price2num($this->qty); - $this->vatrate = price2num($this->vatrate); - if (empty($this->fk_c_exp_tax_cat)) { - $this->fk_c_exp_tax_cat = 0; - } - - $this->db->begin(); - - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det'; - $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,'; - $sql .= ' tva_tx, vat_src_code,'; - $sql .= ' localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; - $sql .= ' comments, qty, value_unit,'; - $sql .= ' total_ht, total_tva, total_ttc,'; - $sql .= ' total_localtax1, total_localtax2,'; - $sql .= ' date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)'; - $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).","; - $sql .= " ".((int) $this->fk_c_type_fees).","; - $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')).","; - $sql .= " ".((float) $this->vatrate).","; - $sql .= " '".$this->db->escape(empty($this->vat_src_code) ? '' : $this->vat_src_code)."',"; - $sql .= " ".((float) price2num($this->localtax1_tx)).","; - $sql .= " ".((float) price2num($this->localtax2_tx)).","; - $sql .= " '".$this->db->escape($this->localtax1_type)."',"; - $sql .= " '".$this->db->escape($this->localtax2_type)."',"; - $sql .= " '".$this->db->escape($this->comments)."',"; - $sql .= " ".((float) $this->qty).","; - $sql .= " ".((float) $this->value_unit).","; - $sql .= " ".((float) price2num($this->total_ht)).","; - $sql .= " ".((float) price2num($this->total_tva)).","; - $sql .= " ".((float) price2num($this->total_ttc)).","; - $sql .= " ".((float) price2num($this->total_localtax1)).","; - $sql .= " ".((float) price2num($this->total_localtax2)).","; - $sql .= " '".$this->db->idate($this->date)."',"; - $sql .= " ".(empty($this->rule_warning_message) ? 'null' : "'".$this->db->escape($this->rule_warning_message)."'").","; - $sql .= " ".((int) $this->fk_c_exp_tax_cat).","; - $sql .= " ".($this->fk_ecm_files > 0 ? ((int) $this->fk_ecm_files) : 'null'); - $sql .= ")"; - - $resql = $this->db->query($sql); - if ($resql) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det'); - - - if (!$error && !$notrigger) { - // Call triggers - $result = $this->call_trigger('EXPENSE_REPORT_DET_CREATE', $user); - if ($result < 0) { - $error++; - } - // End call triggers - } - - - if (!$fromaddline) { + public $comments; + public $qty; + public $value_unit; + public $date; + + /** + * @var int ID + */ + public $fk_c_type_fees; + + /** + * @var int ID + */ + public $fk_c_exp_tax_cat; + + /** + * @var int ID + */ + public $fk_projet; + + /** + * @var int ID + */ + public $fk_expensereport; + + public $type_fees_code; + public $type_fees_libelle; + + public $projet_ref; + public $projet_title; + + public $vatrate; + public $total_ht; + public $total_tva; + public $total_ttc; + + /** + * @var int ID into llx_ecm_files table to link line to attached file + */ + public $fk_ecm_files; + + + /** + * Constructor + * + * @param DoliDB $db Handlet database + */ + public function __construct($db) + { + $this->db = $db; + } + + /** + * Fetch record for expense report detailed line + * + * @param int $rowid Id of object to load + * @return int <0 if KO, >0 if OK + */ + public function fetch($rowid) + { + $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,'; + $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,'; + $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,'; + $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde'; + $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. + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid'; + $sql .= ' WHERE fde.rowid = '.$rowid; + + $result = $this->db->query($sql); + + if ($result) + { + $objp = $this->db->fetch_object($result); + + $this->rowid = $objp->rowid; + $this->id = $objp->rowid; + $this->ref = $objp->ref; + $this->fk_expensereport = $objp->fk_expensereport; + $this->comments = $objp->comments; + $this->qty = $objp->qty; + $this->date = $objp->date; + $this->dates = $this->db->jdate($objp->date); + $this->value_unit = $objp->value_unit; + $this->fk_c_type_fees = $objp->fk_c_type_fees; + $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; + $this->fk_projet = $objp->fk_project; // deprecated + $this->fk_project = $objp->fk_project; + $this->type_fees_code = $objp->type_fees_code; + $this->type_fees_libelle = $objp->type_fees_libelle; + $this->projet_ref = $objp->projet_ref; + $this->projet_title = $objp->projet_title; + $this->vatrate = $objp->vatrate; + $this->vat_src_code = $objp->vat_src_code; + $this->total_ht = $objp->total_ht; + $this->total_tva = $objp->total_tva; + $this->total_ttc = $objp->total_ttc; + $this->fk_ecm_files = $objp->fk_ecm_files; + + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } + + /** + * insert + * + * @param int $notrigger 1=No trigger + * @param bool $fromaddline false=keep default behavior, true=exclude the update_price() of parent object + * @return int <0 if KO, >0 if OK + */ + public function insert($notrigger = 0, $fromaddline = false) + { + global $langs, $user, $conf; + + $error = 0; + + dol_syslog("ExpenseReportLine::Insert rang=".$this->rang, LOG_DEBUG); + + // Clean parameters + $this->comments = trim($this->comments); + if (!$this->value_unit_HT) $this->value_unit_HT = 0; + $this->qty = price2num($this->qty); + $this->vatrate = price2num($this->vatrate); + if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0; + + $this->db->begin(); + + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det'; + $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,'; + $sql .= ' tva_tx, vat_src_code, comments, qty, value_unit, total_ht, total_tva, total_ttc, date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)'; + $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).","; + $sql .= " ".$this->db->escape($this->fk_c_type_fees).","; + $sql .= " ".$this->db->escape($this->fk_project > 0 ? $this->fk_project : ($this->fk_projet > 0 ? $this->fk_projet : 'null')).","; + $sql .= " ".$this->db->escape($this->vatrate).","; + $sql .= " '".$this->db->escape($this->vat_src_code)."',"; + $sql .= " '".$this->db->escape($this->comments)."',"; + $sql .= " ".$this->db->escape($this->qty).","; + $sql .= " ".$this->db->escape($this->value_unit).","; + $sql .= " ".$this->db->escape($this->total_ht).","; + $sql .= " ".$this->db->escape($this->total_tva).","; + $sql .= " ".$this->db->escape($this->total_ttc).","; + $sql .= " '".$this->db->idate($this->date)."',"; + $sql .= " '".$this->db->escape($this->rule_warning_message)."',"; + $sql .= " ".$this->db->escape($this->fk_c_exp_tax_cat).","; + $sql .= " ".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null'); + $sql .= ")"; + + $resql = $this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det'); + + if (!$fromaddline) + { @@ -3072,2 +2697,3 @@ - $result = $tmpparent->update_price(1); - if ($result < 0) { + $result = $tmpparent->update_price(); + if ($result < 0) + { @@ -3079 +2705,3 @@ - } else { + } + else + { @@ -3083,10 +2711,13 @@ - if (!$error) { - $this->db->commit(); - return $this->id; - } else { - $this->error = $this->db->lasterror(); - dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } + if (!$error) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->error = $this->db->lasterror(); + dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } @@ -3109,3 +2740,18 @@ - $sql .= ' WHERE e.fk_user_author = '.((int) $fk_user); - if (!empty($this->id)) { - $sql .= ' AND d.rowid <> '.((int) $this->id); + $sql .= ' WHERE e.fk_user_author = '.$fk_user; + if (!empty($this->id)) $sql .= ' AND d.rowid <> '.$this->id; + $sql .= ' AND d.fk_c_type_fees = '.$rule->fk_c_type_fees; + if ($mode == 'day' || $mode == 'EX_DAY') $sql .= ' AND d.date = \''.dol_print_date($this->date, '%Y-%m-%d').'\''; + elseif ($mode == 'mon' || $mode == 'EX_MON') $sql .= ' AND DATE_FORMAT(d.date, \'%Y-%m\') = \''.dol_print_date($this->date, '%Y-%m').'\''; // @todo DATE_FORMAT is forbidden + elseif ($mode == 'year' || $mode == 'EX_YEA') $sql .= ' AND DATE_FORMAT(d.date, \'%Y\') = \''.dol_print_date($this->date, '%Y').'\''; // @todo DATE_FORMAT is forbidden + + dol_syslog('ExpenseReportLine::getExpAmount'); + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num > 0) + { + $obj = $this->db->fetch_object($resql); + $amount = (double) $obj->total_amount; + } @@ -3113,19 +2759,2 @@ - $sql .= ' AND d.fk_c_type_fees = '.((int) $rule->fk_c_type_fees); - if ($mode == 'day' || $mode == 'EX_DAY') { - $sql .= " AND d.date = '".dol_print_date($this->date, '%Y-%m-%d')."'"; - } elseif ($mode == 'mon' || $mode == 'EX_MON') { - $sql .= " AND DATE_FORMAT(d.date, '%Y-%m') = '".dol_print_date($this->date, '%Y-%m')."'"; // @todo DATE_FORMAT is forbidden - } elseif ($mode == 'year' || $mode == 'EX_YEA') { - $sql .= " AND DATE_FORMAT(d.date, '%Y') = '".dol_print_date($this->date, '%Y')."'"; // @todo DATE_FORMAT is forbidden - } - - dol_syslog('ExpenseReportLine::getExpAmount'); - - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - if ($num > 0) { - $obj = $this->db->fetch_object($resql); - $amount = (float) $obj->total_amount; - } - } else { + else + { @@ -3138,89 +2767,83 @@ - /** - * Update line - * - * @param User $user User - * @return int Return integer <0 if KO, >0 if OK - */ - public function update(User $user) - { - global $langs, $conf; - - $error = 0; - - // Clean parameters - $this->comments = trim($this->comments); - $this->vatrate = price2num($this->vatrate); - $this->value_unit = price2num($this->value_unit); - if (empty($this->fk_c_exp_tax_cat)) { - $this->fk_c_exp_tax_cat = 0; - } - - $this->db->begin(); - - // Update line in database - $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET"; - $sql .= " comments='".$this->db->escape($this->comments)."'"; - $sql .= ", value_unit = ".((float) $this->value_unit); - $sql .= ", qty=".((float) $this->qty); - $sql .= ", date='".$this->db->idate($this->date)."'"; - $sql .= ", total_ht=".((float) price2num($this->total_ht, 'MT')); - $sql .= ", total_tva=".((float) price2num($this->total_tva, 'MT')); - $sql .= ", total_ttc=".((float) price2num($this->total_ttc, 'MT')); - $sql .= ", total_localtax1=".((float) price2num($this->total_localtax1, 'MT')); - $sql .= ", total_localtax2=".((float) price2num($this->total_localtax2, 'MT')); - $sql .= ", tva_tx=".((float) $this->vatrate); - $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'"; - $sql .= ", localtax1_tx=".((float) $this->localtax1_tx); - $sql .= ", localtax2_tx=".((float) $this->localtax2_tx); - $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; - $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql .= ", rule_warning_message='".$this->db->escape($this->rule_warning_message)."'"; - $sql .= ", fk_c_exp_tax_cat=".$this->db->escape($this->fk_c_exp_tax_cat); - $sql .= ", fk_ecm_files=".($this->fk_ecm_files > 0 ? ((int) $this->fk_ecm_files) : 'null'); - if ($this->fk_c_type_fees) { - $sql .= ", fk_c_type_fees = ".((int) $this->fk_c_type_fees); - } else { - $sql .= ", fk_c_type_fees=null"; - } - if ($this->fk_project > 0) { - $sql .= ", fk_projet=".((int) $this->fk_project); - } else { - $sql .= ", fk_projet=null"; - } - $sql .= " WHERE rowid = ".((int) ($this->rowid ? $this->rowid : $this->id)); - - dol_syslog("ExpenseReportLine::update"); - - $resql = $this->db->query($sql); - if ($resql) { - $tmpparent = new ExpenseReport($this->db); - $result = $tmpparent->fetch($this->fk_expensereport); - if ($result > 0) { - $result = $tmpparent->update_price(1); - if ($result < 0) { - $error++; - $this->error = $tmpparent->error; - $this->errors = $tmpparent->errors; - } - } else { - $error++; - $this->error = $tmpparent->error; - $this->errors = $tmpparent->errors; - } - } else { - $error++; - dol_print_error($this->db); - } - - if (!$error) { - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } - - // ajouter ici comput_ ... + /** + * Update line + * + * @param User $user User + * @return int <0 if KO, >0 if OK + */ + public function update(User $user) + { + global $langs, $conf; + + $error = 0; + + // Clean parameters + $this->comments = trim($this->comments); + $this->vatrate = price2num($this->vatrate); + $this->value_unit = price2num($this->value_unit); + if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0; + + $this->db->begin(); + + // Update line in database + $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET"; + $sql .= " comments='".$this->db->escape($this->comments)."'"; + $sql .= ",value_unit=".$this->db->escape($this->value_unit); + $sql .= ",qty=".$this->db->escape($this->qty); + $sql .= ",date='".$this->db->idate($this->date)."'"; + $sql .= ",total_ht=".$this->db->escape($this->total_ht).""; + $sql .= ",total_tva=".$this->db->escape($this->total_tva).""; + $sql .= ",total_ttc=".$this->db->escape($this->total_ttc).""; + $sql .= ",tva_tx=".$this->db->escape($this->vatrate); + $sql .= ",vat_src_code='".$this->db->escape($this->vat_src_code)."'"; + $sql .= ",rule_warning_message='".$this->db->escape($this->rule_warning_message)."'"; + $sql .= ",fk_c_exp_tax_cat=".$this->db->escape($this->fk_c_exp_tax_cat); + $sql .= ",fk_ecm_files=".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null'); + if ($this->fk_c_type_fees) $sql .= ",fk_c_type_fees=".$this->db->escape($this->fk_c_type_fees); + else $sql .= ",fk_c_type_fees=null"; + if ($this->fk_project > 0) $sql .= ",fk_projet=".$this->db->escape($this->fk_project); + else $sql .= ",fk_projet=null"; + $sql .= " WHERE rowid = ".$this->db->escape($this->rowid ? $this->rowid : $this->id); + + dol_syslog("ExpenseReportLine::update sql=".$sql); + + $resql = $this->db->query($sql); + if ($resql) + { + $tmpparent = new ExpenseReport($this->db); + $result = $tmpparent->fetch($this->fk_expensereport); + if ($result > 0) + { + $result = $tmpparent->update_price(); + if ($result < 0) + { + $error++; + $this->error = $tmpparent->error; + $this->errors = $tmpparent->errors; + } + } + else + { + $error++; + $this->error = $tmpparent->error; + $this->errors = $tmpparent->errors; + } + } + else + { + $error++; + dol_print_error($this->db); + } + + if (!$error) + { + $this->db->commit(); + return 1; + } + else + { + $this->error = $this->db->lasterror(); + dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } @@ -3227,0 +2851,82 @@ + + +/** + * Retourne la liste deroulante des differents etats d'une note de frais. + * Les valeurs de la liste sont les id de la table c_expensereport_statuts + * + * @param int $selected preselect status + * @param string $htmlname Name of HTML select + * @param int $useempty 1=Add empty line + * @param int $useshortlabel Use short labels + * @return string HTML select with status + */ +function select_expensereport_statut($selected = '', $htmlname = 'fk_statut', $useempty = 1, $useshortlabel = 0) +{ + global $db, $langs; + + $tmpep = new ExpenseReport($db); + + print ''; +} + +/** + * Return list of types of notes with select value = id + * + * @param int $selected Preselected type + * @param string $htmlname Name of field in form + * @param int $showempty Add an empty field + * @param int $active 1=Active only, 0=Unactive only, -1=All + * @return string Select html + */ +function select_type_fees_id($selected = '', $htmlname = 'type', $showempty = 0, $active = 1) +{ + global $db, $langs, $user; + $langs->load("trips"); + + print ''; +} --- /tmp/dsg/dolibarr/htdocs/expensereport/class/github_19.0.3_expensereport_ik.class.php +++ /tmp/dsg/dolibarr/htdocs/expensereport/class/client_expensereport_ik.class.php @@ -25 +25 @@ -require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/coreobject.class.php'; @@ -30 +30 @@ -class ExpenseReportIk extends CommonObject +class ExpenseReportIk extends CoreObject @@ -43 +43 @@ - * @var string Field with ID of parent key if this field has a parent + * @var int Field with ID of parent key if this field has a parent @@ -71,5 +71,4 @@ - - /** - * Attribute object linked with database - * @var array - */ + /** + * Attribute object linked with database + * @var array + */ @@ -79 +78 @@ - ,'fk_range'=>array('type'=>'integer', 'index'=>true) + ,'fk_range'=>array('type'=>'integer', 'index'=>true) @@ -84,68 +83,13 @@ - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct(DoliDB $db) - { - $this->db = $db; - } - - - /** - * Create object into database - * - * @param User $user User that creates - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @return int Return integer <0 if KO, Id of created object if OK - */ - public function create(User $user, $notrigger = false) - { - $resultcreate = $this->createCommon($user, $notrigger); - - //$resultvalidate = $this->validate($user, $notrigger); - - return $resultcreate; - } - - - /** - * Load object in memory from the database - * - * @param int $id Id object - * @param string $ref Ref - * @return int Return integer <0 if KO, 0 if not found, >0 if OK - */ - public function fetch($id, $ref = null) - { - $result = $this->fetchCommon($id, $ref); - - return $result; - } - - - - /** - * Update object into database - * - * @param User $user User that modifies - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @return int Return integer <0 if KO, >0 if OK - */ - public function update(User $user, $notrigger = false) - { - return $this->updateCommon($user, $notrigger); - } - - /** - * Delete object in database - * - * @param User $user User that deletes - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @return int Return integer <0 if KO, >0 if OK - */ - public function delete(User $user, $notrigger = false) - { - return $this->deleteCommon($user, $notrigger); - //return $this->deleteCommon($user, $notrigger, 1); + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB &$db) + { + global $conf; + + parent::__construct($db); + parent::init(); + + $this->errors = array(); @@ -161,2 +105,4 @@ - public function getTaxCategories($mode = 1) - { + public static function getTaxCategories($mode = 1) + { + global $db; + @@ -167,12 +113,10 @@ - $sql .= ' WHERE entity IN (0, '.getEntity($this->element).')'; - if ($mode == 1) { - $sql .= ' AND active = 1'; - } elseif ($mode == 2) { - $sql .= 'AND active = 0'; - } - - dol_syslog(get_called_class().'::getTaxCategories', LOG_DEBUG); - - $resql = $this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { + $sql .= ' WHERE entity IN ('.getEntity('c_exp_tax_cat').')'; + if ($mode == 1) $sql .= ' AND active = 1'; + elseif ($mode == 2) $sql .= 'AND active = 0'; + + dol_syslog(get_called_class().'::getTaxCategories sql='.$sql, LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + while ($obj = $db->fetch_object($resql)) + { @@ -181,2 +125,4 @@ - } else { - dol_print_error($this->db); + } + else + { + dol_print_error($db); @@ -188,9 +134,9 @@ - /** - * Return an array of ranges for a user - * - * @param User $userauthor user author id - * @param int $fk_c_exp_tax_cat category - * @return boolean|array - */ - public function getRangeByUser(User $userauthor, int $fk_c_exp_tax_cat) - { + /** + * Return an array of ranges for a user + * + * @param User $userauthor user author id + * @param int $fk_c_exp_tax_cat category + * @return boolean|array + */ + public static function getRangeByUser(User $userauthor, $fk_c_exp_tax_cat) + { @@ -198,3 +144,2 @@ - $ranges = $this->getRangesByCategory($fk_c_exp_tax_cat); - // prevent out of range -1 indice - $indice = $default_range - 1; + $ranges = self::getRangesByCategory($fk_c_exp_tax_cat); + @@ -202,5 +147,2 @@ - if (empty($ranges) || $indice < 0 || !isset($ranges[$indice])) { - return false; - } else { - return $ranges[$indice]; - } + if (empty($ranges) || !isset($ranges[$default_range - 1])) return false; + else return $ranges[$default_range - 1]; @@ -216,2 +158,4 @@ - public function getRangesByCategory(int $fk_c_exp_tax_cat, $active = 1) - { + public static function getRangesByCategory($fk_c_exp_tax_cat, $active = 1) + { + global $db; + @@ -220,2 +163,0 @@ - dol_syslog(get_called_class().'::getRangesByCategory for fk_c_exp_tax_cat='.$fk_c_exp_tax_cat, LOG_DEBUG); - @@ -223,8 +165,3 @@ - if ($active) { - $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_exp_tax_cat c ON (r.fk_c_exp_tax_cat = c.rowid)'; - } - $sql .= ' WHERE r.fk_c_exp_tax_cat = '.((int) $fk_c_exp_tax_cat); - $sql .= " AND r.entity IN(0, ".getEntity($this->element).")"; - if ($active) { - $sql .= ' AND r.active = 1 AND c.active = 1'; - } + if ($active) $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_exp_tax_cat c ON (r.fk_c_exp_tax_cat = c.rowid)'; + $sql .= ' WHERE r.fk_c_exp_tax_cat = '.$fk_c_exp_tax_cat; + if ($active) $sql .= ' AND r.active = 1 AND c.active = 1'; @@ -233,6 +170,10 @@ - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - if ($num > 0) { - while ($obj = $this->db->fetch_object($resql)) { - $object = new ExpenseReportIk($this->db); + dol_syslog(get_called_class().'::getRangesByCategory sql='.$sql, LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + if ($num > 0) + { + while ($obj = $db->fetch_object($resql)) + { + $object = new ExpenseReportIk($db); @@ -244,2 +185,4 @@ - } else { - dol_print_error($this->db); + } + else + { + dol_print_error($db); @@ -256,2 +199,4 @@ - public function getAllRanges() - { + public static function getAllRanges() + { + global $db; + @@ -264 +209 @@ - $sql .= ' WHERE r.entity IN (0, '.getEntity($this->element).')'; + $sql .= ' WHERE r.entity IN (0, '.getEntity('').')'; @@ -267,11 +212,8 @@ - dol_syslog(get_called_class().'::getAllRanges', LOG_DEBUG); - - $resql = $this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { - $ik = new ExpenseReportIk($this->db); - if ($obj->fk_expense_ik > 0) { - $ik->fetch($obj->fk_expense_ik); - } - - // TODO Set a $tmparay = new stdObj(); and use it to fill $ranges array + dol_syslog(get_called_class().'::getAllRanges sql='.$sql, LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + while ($obj = $db->fetch_object($resql)) + { + $ik = new ExpenseReportIk($db); + if ($obj->fk_expense_ik > 0) $ik->fetch($obj->fk_expense_ik); @@ -280,3 +222 @@ - if (!isset($ranges[$obj->fk_c_exp_tax_cat])) { - $ranges[$obj->fk_c_exp_tax_cat] = array('label' => $obj->label, 'active' => $obj->cat_active, 'ranges' => array()); - } + if (!isset($ranges[$obj->fk_c_exp_tax_cat])) $ranges[$obj->fk_c_exp_tax_cat] = array('label' => $obj->label, 'active' => $obj->cat_active, 'ranges' => array()); @@ -285,2 +225,4 @@ - } else { - dol_print_error($this->db); + } + else + { + dol_print_error($db); @@ -295,5 +237,7 @@ - * @param int $default_c_exp_tax_cat id Default c_exp_tax_cat - * @return int Max nb - */ - public function getMaxRangeNumber($default_c_exp_tax_cat = 0) - { + * @param int $default_c_exp_tax_cat id + * @return int + */ + public static function getMaxRangeNumber($default_c_exp_tax_cat = 0) + { + global $db, $conf; + @@ -303,4 +247,2 @@ - $sql .= ' WHERE r.entity IN (0, '.getEntity($this->element).')'; - if ($default_c_exp_tax_cat > 0) { - $sql .= ' AND r.fk_c_exp_tax_cat = '.((int) $default_c_exp_tax_cat); - } + $sql .= ' WHERE r.entity IN (0, '.$conf->entity.')'; + if ($default_c_exp_tax_cat > 0) $sql .= ' AND r.fk_c_exp_tax_cat = '.$default_c_exp_tax_cat; @@ -310,4 +252,5 @@ - dol_syslog(get_called_class().'::getMaxRangeNumber', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_called_class().'::getMaxRangeNumber sql='.$sql, LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); @@ -315,2 +258,4 @@ - } else { - dol_print_error($this->db); + } + else + { + dol_print_error($db); --- /tmp/dsg/dolibarr/htdocs/expensereport/class/github_19.0.3_expensereport_rule.class.php +++ /tmp/dsg/dolibarr/htdocs/expensereport/class/client_expensereport_rule.class.php @@ -25 +25 @@ -require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/coreobject.class.php'; @@ -30 +30 @@ -class ExpenseReportRule extends CommonObject +class ExpenseReportRule extends CoreObject @@ -43 +43 @@ - * @var string Fieldname with ID of parent key if this field has a parent + * @var int Field with ID of parent key if this field has a parent @@ -128 +127,0 @@ - @@ -134,78 +133,9 @@ - public function __construct(DoliDB $db) - { - $this->db = $db; - } - - - /** - * Create object into database - * - * @param User $user User that creates - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @return int Return integer <0 if KO, Id of created object if OK - */ - public function create(User $user, $notrigger = false) - { - $resultcreate = $this->createCommon($user, $notrigger); - - //$resultvalidate = $this->validate($user, $notrigger); - - return $resultcreate; - } - - - /** - * Load object in memory from the database - * - * @param int $id Id object - * @param string $ref Ref - * @return int Return integer <0 if KO, 0 if not found, >0 if OK - */ - public function fetch($id, $ref = null) - { - $result = $this->fetchCommon($id, $ref); - if ($result > 0 && !empty($this->table_element_line)) { - $this->fetchLines(); - } - return $result; - } - - - /** - * Load object lines in memory from the database - * - * @return int Return integer <0 if KO, 0 if not found, >0 if OK - */ - public function fetchLines() - { - $this->lines = array(); - - $result = $this->fetchLinesCommon(); - return $result; - } - - /** - * Update object into database - * - * @param User $user User that modifies - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @return int Return integer <0 if KO, >0 if OK - */ - public function update(User $user, $notrigger = false) - { - return $this->updateCommon($user, $notrigger); - } - - /** - * Delete object in database - * - * @param User $user User that deletes - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @return int Return integer <0 if KO, >0 if OK - */ - public function delete(User $user, $notrigger = false) - { - return $this->deleteCommon($user, $notrigger); - //return $this->deleteCommon($user, $notrigger, 1); - } - + public function __construct(DoliDB &$db) + { + global $conf; + + parent::__construct($db); + parent::init(); + + $this->errors = array(); + } @@ -221,2 +151,4 @@ - public function getAllRule($fk_c_type_fees = '', $date = '', $fk_user = '') - { + public static function getAllRule($fk_c_type_fees = '', $date = '', $fk_user = '') + { + global $db; + @@ -224 +155,0 @@ - @@ -227,9 +158,13 @@ - $sql .= ' WHERE er.entity IN (0,'.getEntity($this->element).')'; - if (!empty($fk_c_type_fees)) { - $sql .= ' AND er.fk_c_type_fees IN (-1, '.((int) $fk_c_type_fees).')'; - } - if (!empty($date)) { - $sql .= " AND er.dates <= '".$this->db->idate($date)."'"; - $sql .= " AND er.datee >= '".$this->db->idate($date)."'"; - } - if ($fk_user > 0) { + $sql .= ' WHERE er.entity IN (0,'.getEntity('').')'; + if (!empty($fk_c_type_fees)) + { + $sql .= ' AND er.fk_c_type_fees IN (-1, '.$fk_c_type_fees.')'; + } + if (!empty($date)) + { + $date = dol_print_date($date, '%Y-%m-%d'); + $sql .= ' AND er.dates <= \''.$date.'\''; + $sql .= ' AND er.datee >= \''.$date.'\''; + } + if ($fk_user > 0) + { @@ -237,2 +172,2 @@ - $sql .= ' OR er.fk_user = '.((int) $fk_user); - $sql .= ' OR er.fk_usergroup IN (SELECT ugu.fk_usergroup FROM '.MAIN_DB_PREFIX.'usergroup_user ugu WHERE ugu.fk_user = '.((int) $fk_user).') )'; + $sql .= ' OR er.fk_user = '.$fk_user; + $sql .= ' OR er.fk_usergroup IN (SELECT ugu.fk_usergroup FROM '.MAIN_DB_PREFIX.'usergroup_user ugu WHERE ugu.fk_user = '.$fk_user.') )'; @@ -242,14 +177,15 @@ - dol_syslog("ExpenseReportRule::getAllRule"); - - $resql = $this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { - $rule = new ExpenseReportRule($this->db); - if ($rule->fetch($obj->rowid) > 0) { - $rules[$rule->id] = $rule; - } else { - dol_print_error($this->db); - } - } - } else { - dol_print_error($this->db); + dol_syslog("ExpenseReportRule::getAllRule sql=".$sql); + + $resql = $db->query($sql); + if ($resql) + { + while ($obj = $db->fetch_object($resql)) + { + $rule = new ExpenseReportRule($db); + if ($rule->fetch($obj->rowid) > 0) $rules[$rule->id] = $rule; + else dol_print_error($db); + } + } + else + { + dol_print_error($db); @@ -270 +206,2 @@ - if ($this->fk_usergroup > 0) { + if ($this->fk_usergroup > 0) + { @@ -272,3 +209,6 @@ - if ($group->fetch($this->fk_usergroup) > 0) { - return $group->name; - } else { + if ($group->fetch($this->fk_usergroup) > 0) + { + return $group->nom; + } + else + { @@ -292 +232,2 @@ - if ($this->fk_user > 0) { + if ($this->fk_user > 0) + { @@ -294 +235,2 @@ - if ($u->fetch($this->fk_user) > 0) { + if ($u->fetch($this->fk_user) > 0) + { @@ -296 +238,3 @@ - } else { + } + else + { --- /tmp/dsg/dolibarr/htdocs/expensereport/class/github_19.0.3_expensereportstats.class.php +++ /tmp/dsg/dolibarr/htdocs/expensereport/class/client_expensereportstats.class.php @@ -33 +33 @@ - /** + /** @@ -38,2 +38,2 @@ - public $socid; - public $userid; + public $socid; + public $userid; @@ -41,3 +41,3 @@ - public $from; - public $field; - public $where; + public $from; + public $field; + public $where; @@ -45 +45 @@ - private $datetouse = 'date_valid'; + private $datetouse = 'date_valid'; @@ -53 +53 @@ - * @param int $userid Id user for filter + * @param int $userid Id user for filter @@ -61,2 +61,2 @@ - $this->socid = $socid; - $this->userid = $userid; + $this->socid = $socid; + $this->userid = $userid; @@ -73,2 +73,3 @@ - if ($this->socid) { - $this->where .= " AND e.fk_soc = ".((int) $this->socid); + if ($this->socid) + { + $this->where .= " AND e.fk_soc = ".$this->socid; @@ -78 +79,2 @@ - if (!$user->hasRight('expensereport', 'readall') && !$user->hasRight('expensereport', 'lire_tous')) { + if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) + { @@ -81 +83 @@ - $this->where .= " AND e.fk_user_author IN (".$this->db->sanitize(join(',', $childids)).")"; + $this->where .= " AND e.fk_user_author IN (".(join(',', $childids)).")"; @@ -84,3 +86 @@ - if ($this->userid > 0) { - $this->where .= ' AND e.fk_user_author = '.((int) $this->userid); - } + if ($this->userid > 0) $this->where .= ' AND e.fk_user_author = '.$this->userid; @@ -97 +97 @@ - $sql = "SELECT YEAR(".$this->db->ifsql("e.".$this->datetouse." IS NULL", "e.date_create", "e.".$this->datetouse).") as dm, count(*)"; + $sql = "SELECT YEAR(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).") as dm, count(*)"; @@ -110 +110 @@ - * @param int $format 0=Label of abscissa is a translated text, 1=Label of abscissa is month number, 2=Label of abscissa is first letter of month + * @param int $format 0=Label of abscissa is a translated text, 1=Label of abscissa is month number, 2=Label of abscissa is first letter of month @@ -115 +115 @@ - $sql = "SELECT MONTH(".$this->db->ifsql("e.".$this->datetouse." IS NULL", "e.date_create", "e.".$this->datetouse).") as dm, count(*)"; + $sql = "SELECT MONTH(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).") as dm, count(*)"; @@ -117 +117 @@ - $sql .= " WHERE YEAR(e.".$this->datetouse.") = ".((int) $year); + $sql .= " WHERE YEAR(e.".$this->datetouse.") = ".$year; @@ -120 +120 @@ - $sql .= $this->db->order('dm', 'DESC'); + $sql .= $this->db->order('dm', 'DESC'); @@ -132 +132 @@ - * @param int $format 0=Label of abscissa is a translated text, 1=Label of abscissa is month number, 2=Label of abscissa is first letter of month + * @param int $format 0=Label of abscissa is a translated text, 1=Label of abscissa is month number, 2=Label of abscissa is first letter of month @@ -137 +137 @@ - $sql = "SELECT date_format(".$this->db->ifsql("e.".$this->datetouse." IS NULL", "e.date_create", "e.".$this->datetouse).",'%m') as dm, sum(".$this->field.")"; + $sql = "SELECT date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%m') as dm, sum(".$this->field.")"; @@ -139 +139 @@ - $sql .= " WHERE date_format(".$this->db->ifsql("e.".$this->datetouse." IS NULL", "e.date_create", "e.".$this->datetouse).",'%Y') = '".$this->db->escape($year)."'"; + $sql .= " WHERE date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') = '".$year."'"; @@ -157 +157 @@ - $sql = "SELECT date_format(".$this->db->ifsql("e.".$this->datetouse." IS NULL", "e.date_create", "e.".$this->datetouse).",'%m') as dm, avg(".$this->field.")"; + $sql = "SELECT date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%m') as dm, avg(".$this->field.")"; @@ -159 +159 @@ - $sql .= " WHERE date_format(".$this->db->ifsql("e.".$this->datetouse." IS NULL", "e.date_create", "e.".$this->datetouse).",'%Y') = '".$this->db->escape($year)."'"; + $sql .= " WHERE date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') = '".$year."'"; @@ -162 +162 @@ - $sql .= $this->db->order('dm', 'DESC'); + $sql .= $this->db->order('dm', 'DESC'); @@ -174 +174 @@ - $sql = "SELECT date_format(".$this->db->ifsql("e.".$this->datetouse." IS NULL", "e.date_create", "e.".$this->datetouse).",'%Y') as year, count(*) as nb, sum(".$this->field.") as total, avg(".$this->field.") as avg"; + $sql = "SELECT date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') as year, count(*) as nb, sum(".$this->field.") as total, avg(".$this->field.") as avg"; @@ -178 +178 @@ - $sql .= $this->db->order('year', 'DESC'); + $sql .= $this->db->order('year', 'DESC'); @@ -180,2 +180,2 @@ - return $this->_getAllByYear($sql); - } + return $this->_getAllByYear($sql); + } --- /tmp/dsg/dolibarr/htdocs/expensereport/class/github_19.0.3_paymentexpensereport.class.php +++ /tmp/dsg/dolibarr/htdocs/expensereport/class/client_paymentexpensereport.class.php @@ -43 +43 @@ - /** + /** @@ -54,2 +54,2 @@ - * @var int ID - */ + * @var int ID + */ @@ -61,6 +61,6 @@ - public $amount; // Total amount of payment - public $amounts = array(); // Array of amounts - - /** - * @var int ID - */ + public $amount; // Total amount of payment + public $amounts = array(); // Array of amounts + + /** + * @var int ID + */ @@ -72,2 +72,2 @@ - * @var int ID - */ + * @var int ID + */ @@ -77,2 +77,2 @@ - * @var int ID - */ + * @var int ID + */ @@ -82,2 +82,2 @@ - * @var int ID - */ + * @var int ID + */ @@ -86,17 +86,2 @@ - public $type_code; - public $type_label; - - /** - * @var int - */ - public $bank_account; - - /** - * @var int - */ - public $bank_line; - - /** - * @var string - */ - public $label; + public $type_code; + public $type_label; @@ -117,2 +102,2 @@ - * Use this->amounts to have list of lines for the payment - * + * Use this->amounts to have list of lines for the payment + * @@ -120 +105 @@ - * @return int Return integer <0 if KO, id of payment if OK + * @return int <0 if KO, id of payment if OK @@ -128,3 +113,4 @@ - $now = dol_now(); - // Validate parameters - if (!$this->datep) { + $now = dol_now(); + + // Validate parameters + if (!$this->datepaid) { @@ -136,43 +122,21 @@ - if (isset($this->fk_expensereport)) { - $this->fk_expensereport = trim($this->fk_expensereport); - } - if (isset($this->amount)) { - $this->amount = trim($this->amount); - } - if (isset($this->fk_typepayment)) { - $this->fk_typepayment = trim($this->fk_typepayment); - } - if (isset($this->num_payment)) { - $this->num_payment = trim($this->num_payment); - } - if (isset($this->note)) { - $this->note = trim($this->note); - } - if (isset($this->note_public)) { - $this->note_public = trim($this->note_public); - } - if (isset($this->note_private)) { - $this->note_private = trim($this->note_private); - } - if (isset($this->fk_bank)) { - $this->fk_bank = ((int) $this->fk_bank); - } - if (isset($this->fk_user_creat)) { - $this->fk_user_creat = ((int) $this->fk_user_creat); - } - if (isset($this->fk_user_modif)) { - $this->fk_user_modif = ((int) $this->fk_user_modif); - } - - $totalamount = 0; - foreach ($this->amounts as $key => $value) { // How payment is dispatch - $newvalue = price2num($value, 'MT'); - $this->amounts[$key] = $newvalue; - $totalamount += $newvalue; - } - $totalamount = price2num($totalamount); - - // Check parameters - if ($totalamount == 0) { - return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null - } + if (isset($this->fk_expensereport)) $this->fk_expensereport = trim($this->fk_expensereport); + if (isset($this->amount)) $this->amount = trim($this->amount); + if (isset($this->fk_typepayment)) $this->fk_typepayment = trim($this->fk_typepayment); + if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); + if (isset($this->note)) $this->note = trim($this->note); + if (isset($this->note_public)) $this->note_public = trim($this->note_public); + if (isset($this->fk_bank)) $this->fk_bank = trim($this->fk_bank); + if (isset($this->fk_user_creat)) $this->fk_user_creat = trim($this->fk_user_creat); + if (isset($this->fk_user_modif)) $this->fk_user_modif = trim($this->fk_user_modif); + + $totalamount = 0; + foreach ($this->amounts as $key => $value) // How payment is dispatch + { + $newvalue = price2num($value, 'MT'); + $this->amounts[$key] = $newvalue; + $totalamount += $newvalue; + } + $totalamount = price2num($totalamount); + + // Check parameters + if ($totalamount == 0) return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null @@ -183 +147,2 @@ - if ($totalamount != 0) { + if ($totalamount != 0) + { @@ -187,4 +152,4 @@ - $sql .= " '".$this->db->idate($this->datep)."',"; - $sql .= " ".price2num($totalamount).","; - $sql .= " ".((int) $this->fk_typepayment).", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note_public)."', ".((int) $user->id).","; - $sql .= " 0)"; // fk_bank is ID of transaction into ll_bank + $sql .= " '".$this->db->idate($this->datepaid)."',"; + $sql .= " ".$totalamount.","; + $sql .= " ".$this->fk_typepayment.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note_public)."', ".$user->id.","; + $sql .= " 0)"; @@ -194 +159,2 @@ - if ($resql) { + if ($resql) + { @@ -196 +162,3 @@ - } else { + } + else + { @@ -201,3 +169,4 @@ - if ($totalamount != 0 && !$error) { - $this->amount = $totalamount; - $this->db->commit(); + if ($totalamount != 0 && !$error) + { + $this->amount = $totalamount; + $this->db->commit(); @@ -205 +174,3 @@ - } else { + } + else + { @@ -216 +187 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -238 +209 @@ - $sql .= " WHERE t.rowid = ".((int) $id); + $sql .= " WHERE t.rowid = ".$id; @@ -242,2 +213,4 @@ - if ($resql) { - if ($this->db->num_rows($resql)) { + if ($resql) + { + if ($this->db->num_rows($resql)) + { @@ -270 +243,3 @@ - } else { + } + else + { @@ -276 +251 @@ - // phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter + // phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter @@ -282 +257 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -292,24 +267,8 @@ - if (isset($this->fk_expensereport)) { - $this->fk_expensereport = trim($this->fk_expensereport); - } - if (isset($this->amount)) { - $this->amount = trim($this->amount); - } - if (isset($this->fk_typepayment)) { - $this->fk_typepayment = trim($this->fk_typepayment); - } - if (isset($this->num_payment)) { - $this->num_payment = trim($this->num_payment); - } - if (isset($this->note)) { - $this->note = trim($this->note); - } - if (isset($this->fk_bank)) { - $this->fk_bank = trim($this->fk_bank); - } - if (isset($this->fk_user_creat)) { - $this->fk_user_creat = trim($this->fk_user_creat); - } - if (isset($this->fk_user_modif)) { - $this->fk_user_modif = trim($this->fk_user_modif); - } + if (isset($this->fk_expensereport)) $this->fk_expensereport = trim($this->fk_expensereport); + if (isset($this->amount)) $this->amount = trim($this->amount); + if (isset($this->fk_typepayment)) $this->fk_typepayment = trim($this->fk_typepayment); + if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); + if (isset($this->note)) $this->note = trim($this->note); + if (isset($this->fk_bank)) $this->fk_bank = trim($this->fk_bank); + if (isset($this->fk_user_creat)) $this->fk_user_creat = trim($this->fk_user_creat); + if (isset($this->fk_user_modif)) $this->fk_user_modif = trim($this->fk_user_modif); @@ -334,4 +293,4 @@ - $sql .= " fk_user_modif=".(isset($this->fk_user_modif) ? $this->fk_user_modif : "null"); - - - $sql .= " WHERE rowid=".((int) $this->id); + $sql .= " fk_user_modif=".(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").""; + + + $sql .= " WHERE rowid=".$this->id; @@ -343,4 +302 @@ - if (!$resql) { - $error++; - $this->errors[] = "Error ".$this->db->lasterror(); - } + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } @@ -349,2 +305,4 @@ - if ($error) { - foreach ($this->errors as $errmsg) { + if ($error) + { + foreach ($this->errors as $errmsg) + { @@ -356 +314,3 @@ - } else { + } + else + { @@ -362 +322 @@ - // phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter + // phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter @@ -368 +328 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -378,3 +338,14 @@ - if (!$error) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url"; - $sql .= " WHERE type='payment_expensereport' AND url_id=".((int) $this->id); + if (!$error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url"; + $sql .= " WHERE type='payment_expensereport' AND url_id=".$this->id; + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + } + + if (!$error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_expensereport"; + $sql .= " WHERE rowid=".$this->id; @@ -385,15 +356,3 @@ - $error++; - $this->errors[] = "Error ".$this->db->lasterror(); - } - } - - if (!$error) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_expensereport"; - $sql .= " WHERE rowid=".((int) $this->id); - - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { - $error++; - $this->errors[] = "Error ".$this->db->lasterror(); - } + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } @@ -403,2 +362,4 @@ - if ($error) { - foreach ($this->errors as $errmsg) { + if ($error) + { + foreach ($this->errors as $errmsg) + { @@ -410 +371,3 @@ - } else { + } + else + { @@ -446 +409,2 @@ - if ($result < 0) { + if ($result < 0) + { @@ -454 +418,2 @@ - if (!$error) { + if (!$error) + { @@ -457 +422,3 @@ - } else { + } + else + { @@ -465,4 +432,4 @@ - * Return the label of the status - * - * @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 - * @return string Label of status + * Retourne le libelle du statut d'un don (brouillon, validee, abandonnee, payee) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long + * @return string Libelle @@ -472,26 +439,26 @@ - return ''; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return the label of a given status - * - * @param int $status Id status - * @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 - * @return string Label of status - */ - public function LibStatut($status, $mode = 0) - { - // phpcs:enable - //global $langs; - - return ''; - } - - - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void + return ''; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Renvoi le libelle d'un statut donne + * + * @param int $status Id status + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle du statut + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + global $langs; + + return ''; + } + + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void @@ -517,104 +484,113 @@ - /** - * Add record into bank for payment with links between this bank record and invoices of payment. - * All payment properties must have been set first like after a call to create(). - * - * @param User $user Object of user making payment - * @param string $mode 'payment_expensereport' - * @param string $label Label to use in bank record - * @param int $accountid Id of bank account to do link with - * @param string $emetteur_nom Name of transmitter - * @param string $emetteur_banque Name of bank - * @return int Return integer <0 if KO, >0 if OK - */ - public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque) - { - global $langs, $conf; - - $error = 0; - - if (isModEnabled("banque")) { - include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - - $acc = new Account($this->db); - $acc->fetch($accountid); - - //Fix me field - $total = $this->amount; - - if ($mode == 'payment_expensereport') { - $amount = $total; - } - - // Insert payment into llx_bank - $bank_line_id = $acc->addline( - $this->datep, - $this->fk_typepayment, // Payment mode id or code ("CHQ or VIR for example") - $label, - -$amount, - $this->num_payment, - '', - $user, - $emetteur_nom, - $emetteur_banque - ); - - // Update fk_bank in llx_paiement. - // So we wil know the payment that have generated the bank transaction - if ($bank_line_id > 0) { - $result = $this->update_fk_bank($bank_line_id); - if ($result <= 0) { - $error++; - dol_print_error($this->db); - } - - // Add link 'payment', 'payment_supplier', 'payment_expensereport' in bank_url between payment and bank transaction - $url = ''; - if ($mode == 'payment_expensereport') { - $url = DOL_URL_ROOT.'/expensereport/payment/card.php?rowid='; - } - if ($url) { - $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); - if ($result <= 0) { - $error++; - dol_print_error($this->db); - } - } - - // Add link 'user' in bank_url between user and bank transaction - if (!$error) { - foreach ($this->amounts as $key => $value) { // We should have always same user but we loop in case of. - if ($mode == 'payment_expensereport') { - $fuser = new User($this->db); - $fuser->fetch($key); - - $result = $acc->add_url_line( - $bank_line_id, - $fuser->id, - DOL_URL_ROOT.'/user/card.php?id=', - $fuser->getFullName($langs), - 'user' - ); - if ($result <= 0) { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this).'::addPaymentToBank '.$this->error); - $error++; - } - } - } - } - } else { - $this->error = $acc->error; - $this->errors = $acc->errors; - $error++; - } - } - - if (!$error) { - return 1; - } else { - return -1; - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Add record into bank for payment with links between this bank record and invoices of payment. + * All payment properties must have been set first like after a call to create(). + * + * @param User $user Object of user making payment + * @param string $mode 'payment_expensereport' + * @param string $label Label to use in bank record + * @param int $accountid Id of bank account to do link with + * @param string $emetteur_nom Name of transmitter + * @param string $emetteur_banque Name of bank + * @return int <0 if KO, >0 if OK + */ + public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque) + { + global $langs, $conf; + + $error = 0; + + if (!empty($conf->banque->enabled)) + { + include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + + $acc = new Account($this->db); + $acc->fetch($accountid); + + //Fix me field + $total = $this->amount; + + if ($mode == 'payment_expensereport') $amount = $total; + + // Insert payment into llx_bank + $bank_line_id = $acc->addline( + $this->datepaid, + $this->fk_typepayment, // Payment mode id or code ("CHQ or VIR for example") + $label, + -$amount, + $this->num_payment, + '', + $user, + $emetteur_nom, + $emetteur_banque + ); + + // Update fk_bank in llx_paiement. + // On connait ainsi le paiement qui a genere l'ecriture bancaire + if ($bank_line_id > 0) + { + $result = $this->update_fk_bank($bank_line_id); + if ($result <= 0) + { + $error++; + dol_print_error($this->db); + } + + // Add link 'payment', 'payment_supplier', 'payment_expensereport' in bank_url between payment and bank transaction + $url = ''; + if ($mode == 'payment_expensereport') $url = DOL_URL_ROOT.'/expensereport/payment/card.php?rowid='; + if ($url) + { + $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); + if ($result <= 0) + { + $error++; + dol_print_error($this->db); + } + } + + // Add link 'user' in bank_url between user and bank transaction + if (!$error) + { + foreach ($this->amounts as $key => $value) // We should have always same user but we loop in case of. + { + if ($mode == 'payment_expensereport') + { + $fuser = new User($this->db); + $fuser->fetch($key); + + $result = $acc->add_url_line( + $bank_line_id, + $fuser->id, + DOL_URL_ROOT.'/user/card.php?id=', + $fuser->getFullName($langs), + 'user' + ); + if ($result <= 0) + { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this).'::addPaymentToBank '.$this->error); + $error++; + } + } + } + } + } + else + { + $this->error = $acc->error; + $error++; + } + } + + if (!$error) + { + return 1; + } + else + { + return -1; + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -629,2 +605,2 @@ - // phpcs:enable - $sql = "UPDATE ".MAIN_DB_PREFIX."payment_expensereport SET fk_bank = ".((int) $id_bank)." WHERE rowid = ".((int) $this->id); + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."payment_expensereport SET fk_bank = ".$id_bank." WHERE rowid = ".$this->id; @@ -634 +610,2 @@ - if ($result) { + if ($result) + { @@ -636 +613,3 @@ - } else { + } + else + { @@ -651 +630 @@ - global $langs, $hookmanager; + global $langs; @@ -655,15 +634,5 @@ - if (empty($this->ref)) { - $this->ref = $this->label; - } - $label = img_picto('', $this->picto).' '.$langs->trans("Payment").''; - if (isset($this->status)) { - $label .= ' '.$this->getLibStatut(5); - } - if (!empty($this->ref)) { - $label .= '
'.$langs->trans('Ref').': '.$this->ref; - } - if (!empty($this->datep)) { - $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->datep, 'dayhour'); - } - - if (!empty($this->id)) { + if (empty($this->ref)) $this->ref = $this->label; + $label = $langs->trans("ShowPayment").': '.$this->ref; + + if (!empty($this->id)) + { @@ -673,19 +642,5 @@ - if ($withpicto) { - $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); - } - if ($withpicto && $withpicto != 2) { - $result .= ' '; - } - if ($withpicto != 2) { - $result .= $link.($maxlen ? dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; - } - } - global $action; - $hookmanager->initHooks(array($this->element . 'dao')); - $parameters = array('id'=>$this->id, 'getnomurl' => &$result); - $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) { - $result = $hookmanager->resPrint; - } else { - $result .= $hookmanager->resPrint; - } + if ($withpicto) $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + if ($withpicto && $withpicto != 2) $result .= ' '; + if ($withpicto != 2) $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + } + @@ -701,2 +656,2 @@ - public function info($id) - { + public function info($id) + { @@ -705 +660 @@ - $sql .= ' WHERE e.rowid = '.((int) $id); + $sql .= ' WHERE e.rowid = '.$id; @@ -710,2 +665,4 @@ - if ($result) { - if ($this->db->num_rows($result)) { + if ($result) + { + if ($this->db->num_rows($result)) + { @@ -713 +669,0 @@ - @@ -715,3 +671,12 @@ - - $this->user_creation_id = $obj->fk_user_creat; - $this->user_modification_id = $obj->fk_user_modif; + if ($obj->fk_user_creat) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_creat); + $this->user_creation = $cuser; + } + if ($obj->fk_user_modif) + { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_modif); + $this->user_modification = $muser; + } @@ -722 +687,3 @@ - } else { + } + else + { @@ -725,45 +692 @@ - } - - /** - * Return clicable link of object (with eventually picto) - * - * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link) - * @param array $arraydata Array of data - * @return string HTML Code for Kanban thumb. - */ - public function getKanbanView($option = '', $arraydata = null) - { - global $langs; - - $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']); - - $return = '
'; - $return .= '
'; - $return .= ''; - $return .= img_picto('', $this->picto); - $return .= ''; - $return .= '
'; - $return .= ''.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).''; - if ($selected >= 0) { - $return .= ''; - } - if (property_exists($this, 'datep')) { - $return .= '
'.$langs->trans("Date").' : '.dol_print_date($this->db->jdate($this->datep), 'dayhour').''; - } - if (property_exists($this, 'fk_typepayment')) { - $return .= '
'.$langs->trans("Type").' : '.$this->fk_typepayment.''; - } - if (property_exists($this, 'fk_bank') && !is_null($this->fk_bank)) { - $return .= '
'.$langs->trans("Account").' : '.$this->fk_bank.''; - } - if (property_exists($this, 'amount')) { - $return .= '
'.$langs->trans("Amount").' : '.price($this->amount).''; - } - if (method_exists($this, 'getLibStatut')) { - $return .= '
'.$this->getLibStatut(3).'
'; - } - $return .= '
'; - $return .= '
'; - $return .= '
'; - return $return; - } + }