--- /tmp/dsg/dolibarr/htdocs/compta/facture/class/github_api_invoices.class.php +++ /tmp/dsg/dolibarr/htdocs/compta/facture/class/client_api_invoices.class.php @@ -28,96 +28,96 @@ */ class Invoices extends DolibarrApi { - /** - * - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'socid', - ); - - /** - * @var Facture $invoice {@type Facture} - */ - public $invoice; - - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - $this->invoice = new Facture($this->db); - } - - /** - * Get properties of a invoice object - * - * Return an array with invoice informations - * - * @param int $id ID of invoice - * @param int $contact_list 0:Return array contains all properties, 1:Return array contains just id - * @return array|mixed data without useless information - * - * @throws RestException - */ + /** + * + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid', + ); + + /** + * @var Facture $invoice {@type Facture} + */ + public $invoice; + + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + $this->db = $db; + $this->invoice = new Facture($this->db); + } + + /** + * Get properties of a invoice object + * + * Return an array with invoice informations + * + * @param int $id ID of invoice + * @param int $contact_list 0:Return array contains all properties, 1:Return array contains just id + * @return array|mixed data without useless information + * + * @throws RestException + */ public function get($id, $contact_list = 1) { - return $this->_fetch($id, '', '', $contact_list); + return $this->_fetch($id, '', '', $contact_list); } - /** - * Get properties of an invoice object by ref - * - * Return an array with invoice informations - * - * @param string $ref Ref of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @url GET ref/{ref} - * - * @throws RestException - */ - public function getByRef($ref, $contact_list = 1) - { - return $this->_fetch('', $ref, '', $contact_list); - } - - /** - * Get properties of an invoice object by ref_ext - * - * Return an array with invoice informations - * - * @param string $ref_ext External reference of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @url GET ref_ext/{ref_ext} - * - * @throws RestException - */ - public function getByRefExt($ref_ext, $contact_list = 1) - { - return $this->_fetch('', '', $ref_ext, $contact_list); - } - - /** - * Get properties of an invoice object - * - * Return an array with invoice informations - * - * @param int $id ID of order + /** + * Get properties of an invoice object by ref + * + * Return an array with invoice informations + * + * @param string $ref Ref of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref/{ref} + * + * @throws RestException + */ + public function getByRef($ref, $contact_list = 1) + { + return $this->_fetch('', $ref, '', $contact_list); + } + + /** + * Get properties of an invoice object by ref_ext + * + * Return an array with invoice informations + * + * @param string $ref_ext External reference of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref_ext/{ref_ext} + * + * @throws RestException + */ + public function getByRefExt($ref_ext, $contact_list = 1) + { + return $this->_fetch('', '', $ref_ext, $contact_list); + } + + /** + * Get properties of an invoice object + * + * Return an array with invoice informations + * + * @param int $id ID of order * @param string $ref Ref of object * @param string $ref_ext External reference of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @throws RestException - */ - private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) - { + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @throws RestException + */ + private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) + { if (!DolibarrApiAccess::$user->rights->facture->lire) { throw new RestException(401); } @@ -142,138 +142,139 @@ $this->invoice->fetchObjectLinked(); return $this->_cleanObjectDatas($this->invoice); - } - - /** - * List invoices - * - * Get a list of invoices - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $thirdparty_ids Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} - * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled - * @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 invoice objects - * + } + + /** + * List invoices + * + * Get a list of invoices + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $thirdparty_ids Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} + * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled + * @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 invoice objects + * * @throws RestException 404 Not found * @throws RestException 503 Error - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '') - { - global $db, $conf; - - $obj_ret = array(); - - // case of external user, $thirdparty_ids param is ignored and replaced by user's socid - $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; - - // If the internal user must only see his customers, force searching by him - $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; - - $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) - $sql .= " FROM ".MAIN_DB_PREFIX."facture as t"; - - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale - - $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '') + { + global $db, $conf; + + $obj_ret = array(); + + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid + $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; + + // If the internal user must only see his customers, force searching by him + $search_sale = 0; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + + $sql = "SELECT t.rowid"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + $sql .= " FROM ".MAIN_DB_PREFIX."facture as t"; + + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + + $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; + if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; + + if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale // Filter by status - if ($status == 'draft') $sql .= " AND t.fk_statut IN (0)"; - if ($status == 'unpaid') $sql .= " AND t.fk_statut IN (1)"; - if ($status == 'paid') $sql .= " AND t.fk_statut IN (2)"; - if ($status == 'cancelled') $sql .= " AND t.fk_statut IN (3)"; - // Insert sale filter - if ($search_sale > 0) - { - $sql .= " AND sc.fk_user = ".$search_sale; - } - // 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 .= $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) - { - $i = 0; - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { - $obj = $this->db->fetch_object($result); - $invoice_static = new Facture($this->db); - if ($invoice_static->fetch($obj->rowid)) - { - // Get payment details - $invoice_static->totalpaid = $invoice_static->getSommePaiement(); - $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed(); - $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed(); - $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT'); + if ($status == 'draft') $sql .= " AND t.fk_statut IN (0)"; + if ($status == 'unpaid') $sql .= " AND t.fk_statut IN (1)"; + if ($status == 'paid') $sql .= " AND t.fk_statut IN (2)"; + if ($status == 'cancelled') $sql .= " AND t.fk_statut IN (3)"; + // Insert sale filter + if ($search_sale > 0) + { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // 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) + { + $i = 0; + $num = $db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $db->fetch_object($result); + $invoice_static = new Facture($db); + if ($invoice_static->fetch($obj->rowid)) + { + // Get payment details + $invoice_static->totalpaid = $invoice_static->getSommePaiement(); + $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed(); + $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed(); + $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT'); // Add external contacts ids $invoice_static->contacts_ids = $invoice_static->liste_contact(-1, 'external', 1); - $obj_ret[] = $this->_cleanObjectDatas($invoice_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No invoice found'); - } + $obj_ret[] = $this->_cleanObjectDatas($invoice_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve invoice list : '.$db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No invoice found'); + } return $obj_ret; - } - - /** - * Create invoice object - * - * @param array $request_data Request datas - * @return int ID of invoice - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { + } + + /** + * Create invoice object + * + * @param array $request_data Request datas + * @return int ID of invoice + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401, "Insuffisant rights"); } - // Check mandatory fields - $result = $this->_validate($request_data); - - foreach ($request_data as $field => $value) { - $this->invoice->$field = $value; - } - if (!array_key_exists('date', $request_data)) { - $this->invoice->date = dol_now(); - } - /* We keep lines as an array + // Check mandatory fields + $result = $this->_validate($request_data); + + foreach ($request_data as $field => $value) { + $this->invoice->$field = $value; + } + if (!array_key_exists('date', $request_data)) { + $this->invoice->date = dol_now(); + } + /* We keep lines as an array if (isset($request_data["lines"])) { $lines = array(); foreach ($request_data["lines"] as $line) { @@ -282,154 +283,152 @@ $this->invoice->lines = $lines; }*/ - if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) { - throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors)); - } - return $this->invoice->id; - } - - /** - * Create an invoice using an existing order. - * - * - * @param int $orderid Id of the order - * - * @url POST /createfromorder/{orderid} - * - * @return int - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - */ - public function createInvoiceFromOrder($orderid) - { - - require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - - if (!DolibarrApiAccess::$user->rights->commande->lire) { - throw new RestException(401); - } - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - if (empty($orderid)) { - throw new RestException(400, 'Order ID is mandatory'); - } - - $order = new Commande($this->db); - $result = $order->fetch($orderid); - if (!$result) { - throw new RestException(404, 'Order not found'); - } - - $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user); - if ($result < 0) { - throw new RestException(405, $this->invoice->error); - } - $this->invoice->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->invoice); - } - - /** - * Get lines of an invoice - * - * @param int $id Id of invoice - * - * @url GET {id}/lines - * - * @return int - */ - public function getLines($id) - { - if (!DolibarrApiAccess::$user->rights->facture->lire) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->invoice->getLinesArray(); - $result = array(); - foreach ($this->invoice->lines as $line) { - array_push($result, $this->_cleanObjectDatas($line)); - } - return $result; - } - - /** - * Update a line to a given invoice - * - * @param int $id Id of invoice to update - * @param int $lineid Id of line to update - * @param array $request_data InvoiceLine data - * - * @url PUT {id}/lines/{lineid} - * - * @return array - * - * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 Invoice not found - */ - public function putLine($id, $lineid, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->invoice->updateline( - $lineid, - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->remise_percent, - $request_data->date_start, - $request_data->date_end, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - 'HT', - $request_data->info_bits, - $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->situation_percent, - $request_data->fk_unit, - $request_data->multicurrency_subprice, - 0, - $request_data->ref_ext - ); - - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } else { - throw new RestException(304, $this->invoice->error); - } - } - - /** + if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) { + throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors)); + } + return $this->invoice->id; + } + + /** + * Create an invoice using an existing order. + * + * + * @param int $orderid Id of the order + * + * @url POST /createfromorder/{orderid} + * + * @return int + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + */ + public function createInvoiceFromOrder($orderid) + { + + require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; + + if (!DolibarrApiAccess::$user->rights->commande->lire) { + throw new RestException(401); + } + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if (empty($orderid)) { + throw new RestException(400, 'Order ID is mandatory'); + } + + $order = new Commande($this->db); + $result = $order->fetch($orderid); + if (!$result) { + throw new RestException(404, 'Order not found'); + } + + $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user); + if ($result < 0) { + throw new RestException(405, $this->invoice->error); + } + $this->invoice->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->invoice); + } + + /** + * Get lines of an invoice + * + * @param int $id Id of invoice + * + * @url GET {id}/lines + * + * @return int + */ + public function getLines($id) + { + if (!DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->invoice->getLinesArray(); + $result = array(); + foreach ($this->invoice->lines as $line) { + array_push($result, $this->_cleanObjectDatas($line)); + } + return $result; + } + + /** + * Update a line to a given invoice + * + * @param int $id Id of invoice to update + * @param int $lineid Id of line to update + * @param array $request_data InvoiceLine data + * + * @url PUT {id}/lines/{lineid} + * + * @return array + * + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 Invoice not found + */ + public function putLine($id, $lineid, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->invoice->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->date_start, + $request_data->date_end, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $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->situation_percent, + $request_data->fk_unit, + $request_data->multicurrency_subprice + ); + + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } else { + throw new RestException(304, $this->invoice->error); + } + } + + /** * Add a contact type of given invoice * * @param int $id Id of invoice to update @@ -440,1244 +439,1135 @@ * * @return int * - * @throws RestException 401 - * @throws RestException 404 + * @throws RestException 401 + * @throws RestException 404 */ - public function postContact($id, $contactid, $type) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); + public function postContact($id, $contactid, $type) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); if (!$result) { throw new RestException(404, 'Invoice not found'); } - if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) { - throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER'); - } - - if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) { + if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) { + throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER'); + } + + if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $result = $this->invoice->add_contact($contactid, $type, 'external'); - - if (!$result) { - throw new RestException(500, 'Error when added the contact'); - } - - return $this->_cleanObjectDatas($this->invoice); - } - - /** + $result = $this->invoice->add_contact($contactid, $type, 'external'); + + if (!$result) { + throw new RestException(500, 'Error when added the contact'); + } + + return $this->_cleanObjectDatas($this->invoice); + } + + /** * Delete a contact type of given invoice * * @param int $id Id of invoice to update - * @param int $contactid Row key of the contact in the array contact_ids. - * @param string $type Type of the contact (BILLING, SHIPPING, CUSTOMER). + * @param int $rowid Row key of the contact in the array contact_ids. * - * @url DELETE {id}/contact/{contactid}/{type} + * @url DELETE {id}/contact/{rowid} * * @return array - * - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 + * + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 */ - public function deleteContact($id, $contactid, $type) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); + public function deleteContact($id, $rowid) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); if (!$result) { throw new RestException(404, 'Invoice not found'); } - if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) { + if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $contacts = $this->invoice->liste_contact(); - - foreach ($contacts as $contact) { - if ($contact['id'] == $contactid && $contact['code'] == $type) { - $result = $this->invoice->delete_contact($contact['rowid']); - - if (!$result) { - throw new RestException(500, 'Error when deleted the contact'); - } - } - } - - return $this->_cleanObjectDatas($this->invoice); - } - - /** - * Deletes a line of a given invoice - * - * @param int $id Id of invoice - * @param int $lineid Id of the line to delete - * - * @url DELETE {id}/lines/{lineid} - * - * @return array - * - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - */ - public function deleteLine($id, $lineid) - { - - if (!DolibarrApiAccess::$user->rights->facture->creer) { + $result = $this->invoice->delete_contact($rowid); + if ($result < 0) { + throw new RestException(500, 'Error when deleted the contact'); + } + + return $this->_cleanObjectDatas($this->invoice); + } + + /** + * Deletes a line of a given invoice + * + * @param int $id Id of invoice + * @param int $lineid Id of the line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return array + * + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + */ + public function deleteLine($id, $lineid) + { + + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if (empty($lineid)) { + throw new RestException(400, 'Line ID is mandatory'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + // TODO Check the lineid $lineid is a line of ojbect + + $updateRes = $this->invoice->deleteline($lineid); + if ($updateRes > 0) { + return $this->get($id); + } + else + { + throw new RestException(405, $this->invoice->error); + } + } + + /** + * Update invoice + * + * @param int $id Id of invoice to update + * @param array $request_data Datas + * @return int + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401); } - if (empty($lineid)) { - throw new RestException(400, 'Line ID is mandatory'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - // TODO Check the lineid $lineid is a line of ojbect - - $updateRes = $this->invoice->deleteline($lineid); - if ($updateRes > 0) { - return $this->get($id); - } else { - throw new RestException(405, $this->invoice->error); - } - } - - /** - * Update invoice - * - * @param int $id Id of invoice to update - * @param array $request_data Datas - * @return int - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - foreach ($request_data as $field => $value) { - if ($field == 'id') continue; - $this->invoice->$field = $value; - } - - // update bank account - if (!empty($this->invoice->fk_account)) - { - if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) { - throw new RestException(400, $this->invoice->error); - } - } - - if ($this->invoice->update(DolibarrApiAccess::$user)) - return $this->get($id); - - return false; - } - - /** - * Delete invoice - * - * @param int $id Invoice ID - * @return array - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->facture->supprimer) { + foreach ($request_data as $field => $value) { + if ($field == 'id') continue; + $this->invoice->$field = $value; + } + + // update bank account + if (!empty($this->invoice->fk_account)) + { + if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) { + throw new RestException(400, $this->invoice->error); + } + } + + if ($this->invoice->update(DolibarrApiAccess::$user)) + return $this->get($id); + + return false; + } + + /** + * Delete invoice + * + * @param int $id Invoice ID + * @return array + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->facture->supprimer) { throw new RestException(401); } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $result = $this->invoice->delete(DolibarrApiAccess::$user); - if ($result < 0) - { - throw new RestException(500); - } - - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Invoice deleted' - ) - ); - } - - /** - * Add a line to a given invoice + if ($result < 0) + { + throw new RestException(500); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Invoice deleted' + ) + ); + } + + /** + * Add a line to a given invoice + * + * Exemple of POST query : + * { + * "desc": "Desc", "subprice": "1.00000000", "qty": "1", "tva_tx": "20.000", "localtax1_tx": "0.000", "localtax2_tx": "0.000", + * "fk_product": "1", "remise_percent": "0", "date_start": "", "date_end": "", "fk_code_ventilation": 0, "info_bits": "0", + * "fk_remise_except": null, "product_type": "1", "rang": "-1", "special_code": "0", "fk_parent_line": null, "fk_fournprice": null, + * "pa_ht": "0.00000000", "label": "", "array_options": [], "situation_percent": "100", "fk_prev_id": null, "fk_unit": null + * } + * + * @param int $id Id of invoice + * @param array $request_data InvoiceLine data + * + * @url POST {id}/lines + * + * @return int + * + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 400 + */ + public function postLine($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $request_data; + + // Reset fk_parent_line for no child products and special product + if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) { + $request_data->fk_parent_line = 0; + } + + // calculate pa_ht + $marginInfos = getMarginInfos($request_data->subprice, $request_data->remise_percent, $request_data->tva_tx, $request_data->localtax1_tx, $request_data->localtax2_tx, $request_data->fk_fournprice, $request_data->pa_ht); + $pa_ht = $marginInfos[0]; + + $updateRes = $this->invoice->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->date_start, + $request_data->date_end, + $request_data->fk_code_ventilation, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $request_data->origin, + $request_data->origin_id, + $request_data->fk_parent_line, + empty($request_data->fk_fournprice) ?null:$request_data->fk_fournprice, + $pa_ht, + $request_data->label, + $request_data->array_options, + $request_data->situation_percent, + $request_data->fk_prev_id, + $request_data->fk_unit + ); + + if ($updateRes < 0) { + throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error); + } + + return $updateRes; + } + + /** + * Adds a contact to an invoice + * + * @param int $id Order ID + * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link + * @param string $type_contact Type of contact (code). Must a code found into table llx_c_type_contact. For example: BILLING + * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) + * @param int $notrigger Disable all triggers + * + * @url POST {id}/contacts + * + * @return array + * + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 + * + */ + public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger); + if ($result < 0) { + throw new RestException(500, 'Error : '.$this->invoice->error); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + return $this->_cleanObjectDatas($this->invoice); + } + + + + /** + * Sets an invoice as draft + * + * @param int $id Order ID + * @param int $idwarehouse Warehouse ID + * + * @url POST {id}/settodraft + * + * @return array + * + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 + * + */ + public function settodraft($id, $idwarehouse = -1) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse); + if ($result == 0) { + throw new RestException(304, 'Nothing done.'); + } + if ($result < 0) { + throw new RestException(500, 'Error : '.$this->invoice->error); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + return $this->_cleanObjectDatas($this->invoice); + } + + + /** + * Validate an invoice + * + * If you get a bad value for param notrigger check that ou provide this in body + * { + * "idwarehouse": 0, + * "notrigger": 0 + * } + * + * @param int $id Invoice ID + * @param int $idwarehouse Warehouse ID + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * + * @url POST {id}/validate + * + * @return array + */ + public function validate($id, $idwarehouse = 0, $notrigger = 0) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger); + if ($result == 0) { + throw new RestException(304, 'Error nothing done. May be object is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + return $this->_cleanObjectDatas($this->invoice); + } + + /** + * Sets an invoice as paid + * + * @param int $id Order ID + * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple) + * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple) + * + * @url POST {id}/settopaid + * + * @return array An invoice object + * + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 + */ + public function settopaid($id, $close_code = '', $close_note = '') + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->set_paid(DolibarrApiAccess::$user, $close_code, $close_note); + if ($result == 0) { + throw new RestException(304, 'Error nothing done. May be object is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error : '.$this->invoice->error); + } + + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + return $this->_cleanObjectDatas($this->invoice); + } + + + /** + * Sets an invoice as unpaid + * + * @param int $id Order ID + * + * @url POST {id}/settounpaid + * + * @return array An invoice object + * + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 + */ + public function settounpaid($id) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->set_unpaid(DolibarrApiAccess::$user); + if ($result == 0) { + throw new RestException(304, 'Nothing done'); + } + if ($result < 0) { + throw new RestException(500, 'Error : '.$this->invoice->error); + } + + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + return $this->_cleanObjectDatas($this->invoice); + } + + /** + * Create a discount (credit available) for a credit note or a deposit. + * + * @param int $id Invoice ID + * @url POST {id}/markAsCreditAvailable + * + * @return array An invoice object + * + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 + */ + public function markAsCreditAvailable($id) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if ($this->invoice->paye) { + throw new RestException(500, 'Alreay payed'); + } + + $this->invoice->fetch($id); + $this->invoice->fetch_thirdparty(); + + // Check if there is already a discount (protection to avoid duplicate creation when resubmit post) + $discountcheck = new DiscountAbsolute($this->db); + $result = $discountcheck->fetch(0, $this->invoice->id); + + $canconvert = 0; + if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) + if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) + if ($canconvert) + { + $this->db->begin(); + + $amount_ht = $amount_tva = $amount_ttc = array(); + $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array(); + + // Loop on each vat rate + $i = 0; + foreach ($this->invoice->lines as $line) + { + if ($line->product_type < 9 && $line->total_ht != 0) // Remove lines with product_type greater than or equal to 9 + { // no need to create discount if amount is null + $amount_ht[$line->tva_tx] += $line->total_ht; + $amount_tva[$line->tva_tx] += $line->total_tva; + $amount_ttc[$line->tva_tx] += $line->total_ttc; + $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht; + $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva; + $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc; + $i++; + } + } + + // Insert one discount by VAT rate category + $discount = new DiscountAbsolute($this->db); + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { + $discount->description = '(CREDIT_NOTE)'; + } + elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) { + $discount->description = '(DEPOSIT)'; + } + elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) { + $discount->description = '(EXCESS RECEIVED)'; + } + else { + throw new RestException(500, 'Cant convert to reduc an Invoice of this type'); + } + + $discount->fk_soc = $this->invoice->socid; + $discount->fk_facture_source = $this->invoice->id; + + $error = 0; + + if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) + { + // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT + + // Total payments + $sql = 'SELECT SUM(pf.amount) as total_paiements'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; + $sql .= ' WHERE pf.fk_facture = '.$this->invoice->id; + $sql .= ' AND pf.fk_paiement = p.rowid'; + $sql .= ' AND p.entity IN ('.getEntity('invoice').')'; + $resql = $this->db->query($sql); + if (!$resql) dol_print_error($this->db); + + $res = $this->db->fetch_object($resql); + $total_paiements = $res->total_paiements; + + // Total credit note and deposit + $total_creditnote_and_deposit = 0; + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; + $sql .= " re.description, re.fk_facture_source"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re"; + $sql .= " WHERE fk_facture = ".$this->invoice->id; + $resql = $this->db->query($sql); + if (!empty($resql)) { + while ($obj = $this->db->fetch_object($resql)) $total_creditnote_and_deposit += $obj->amount_ttc; + } else dol_print_error($this->db); + + $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $this->invoice->total_ttc; + $discount->amount_tva = 0; + $discount->tva_tx = 0; + + $result = $discount->create(DolibarrApiAccess::$user); + if ($result < 0) + { + $error++; + } + } + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) + { + foreach ($amount_ht as $tva_tx => $xxx) + { + $discount->amount_ht = abs($amount_ht[$tva_tx]); + $discount->amount_tva = abs($amount_tva[$tva_tx]); + $discount->amount_ttc = abs($amount_ttc[$tva_tx]); + $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]); + $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]); + $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]); + $discount->tva_tx = abs($tva_tx); + + $result = $discount->create(DolibarrApiAccess::$user); + if ($result < 0) + { + $error++; + break; + } + } + } + + if (empty($error)) + { + if ($this->invoice->type != Facture::TYPE_DEPOSIT) { + // Classe facture + $result = $this->invoice->set_paid(DolibarrApiAccess::$user); + if ($result >= 0) + { + $this->db->commit(); + } + else + { + $this->db->rollback(); + throw new RestException(500, 'Could not set paid'); + } + } else { + $this->db->commit(); + } + } + else + { + $this->db->rollback(); + throw new RestException(500, 'Discount creation error'); + } + } + + return $this->_cleanObjectDatas($this->invoice); + } + + /** + * Add a discount line into an invoice (as an invoice line) using an existing absolute discount + * + * Note that this consume the discount. + * + * @param int $id Id of invoice + * @param int $discountid Id of discount + * + * @url POST {id}/usediscount/{discountid} + * + * @return int * - * Exemple of POST query : - * { - * "desc": "Desc", "subprice": "1.00000000", "qty": "1", "tva_tx": "20.000", "localtax1_tx": "0.000", "localtax2_tx": "0.000", - * "fk_product": "1", "remise_percent": "0", "date_start": "", "date_end": "", "fk_code_ventilation": 0, "info_bits": "0", - * "fk_remise_except": null, "product_type": "1", "rang": "-1", "special_code": "0", "fk_parent_line": null, "fk_fournprice": null, - * "pa_ht": "0.00000000", "label": "", "array_options": [], "situation_percent": "100", "fk_prev_id": null, "fk_unit": null - * } + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + */ + public function useDiscount($id, $discountid) + { + + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if (empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + if (empty($discountid)) { + throw new RestException(400, 'Discount ID is mandatory'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + $result = $this->invoice->insert_discount($discountid); + if ($result < 0) { + throw new RestException(405, $this->invoice->error); + } + + return $result; + } + + /** + * Add an available credit note discount to payments of an existing invoice. + * + * Note that this consume the credit note. + * + * @param int $id Id of invoice + * @param int $discountid Id of a discount coming from a credit note + * + * @url POST {id}/usecreditnote/{discountid} + * + * @return int + * + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + */ + public function useCreditNote($id, $discountid) + { + + require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if (empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + if (empty($discountid)) { + throw new RestException(400, 'Credit ID is mandatory'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $discount = new DiscountAbsolute($this->db); + $result = $discount->fetch($discountid); + if (!$result) { + throw new RestException(404, 'Credit not found'); + } + + $result = $discount->link_to_invoice(0, $id); + if ($result < 0) { + throw new RestException(405, $discount->error); + } + + return $result; + } + + /** + * Get list of payments of a given invoice + * + * @param int $id Id of invoice + * + * @url GET {id}/payments + * + * @return array * - * @param int $id Id of invoice - * @param array $request_data InvoiceLine data + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + */ + public function getPayments($id) + { + + if (!DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + if (empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + $result = $this->invoice->getListOfPayments(); + if ($result < 0) { + throw new RestException(405, $this->invoice->error); + } + + return $result; + } + + + /** + * Add payment line to a specific invoice with the remain to pay as amount. + * + * @param int $id Id of invoice + * @param string $datepaye {@from body} Payment date {@type timestamp} + * @param int $paiementid {@from body} Payment mode Id {@min 1} + * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} + * @param int $accountid {@from body} Account Id {@min 1} + * @param string $num_paiement {@from body} Payment number (optional) + * @param string $comment {@from body} Note (optional) + * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ') + * @param string $chqbank {@from body} Issuer bank name (optional) + * + * @url POST {id}/payments + * + * @return int Payment ID * - * @url POST {id}/lines + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + */ + public function addPayment($id, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement = '', $comment = '', $chqemetteur = '', $chqbank = '') + { + global $conf; + + require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; + + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(403); + } + if (empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + + if (!DolibarrApi::_checkAccessToResource('facture', $id)) { + throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if (!empty($conf->banque->enabled)) { + if (empty($accountid)) { + throw new RestException(400, 'Account ID is mandatory'); + } + } + + if (empty($paiementid)) { + throw new RestException(400, 'Paiement ID or Paiement Code is mandatory'); + } + + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + // Calculate amount to pay + $totalpaye = $this->invoice->getSommePaiement(); + $totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); + $totaldeposits = $this->invoice->getSumDepositsUsed(); + $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); + + $this->db->begin(); + + $amounts = array(); + $multicurrency_amounts = array(); + + // Clean parameters amount if payment is for a credit note + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { + $resteapayer = price2num($resteapayer, 'MT'); + $amounts[$id] = -$resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); + $multicurrency_amounts[$id] = -$newvalue; + } else { + $resteapayer = price2num($resteapayer, 'MT'); + $amounts[$id] = $resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); + $multicurrency_amounts[$id] = $newvalue; + } + + + // Creation of payment line + $paiement = new Paiement($this->db); + $paiement->datepaye = $datepaye; + $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id + $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching + $paiement->paiementid = $paiementid; + $paiement->paiementcode = dol_getIdFromCode($this->db, $paiementid, 'c_paiement', 'id', 'code', 1); + $paiement->num_paiement = $num_paiement; + $paiement->note = $comment; + + $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices + if ($paiement_id < 0) + { + $this->db->rollback(); + throw new RestException(400, 'Payment error : '.$paiement->error); + } + + if (!empty($conf->banque->enabled)) { + $label = '(CustomerInvoicePayment)'; + + if ($paiement->paiementcode == 'CHQ' && empty($chqemetteur)) { + throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paiement->paiementcode); + } + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note + $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank); + if ($result < 0) + { + $this->db->rollback(); + throw new RestException(400, 'Add payment to bank error : '.$paiement->error); + } + } + + $this->db->commit(); + + return $paiement_id; + } + + /** + * Add a payment to pay partially or completely one or several invoices. + * Warning: Take care that all invoices are owned by the same customer. + * Example of value for parameter arrayofamounts: {"1": "99.99", "2": "10"} + * + * @param array $arrayofamounts {@from body} Array with id of invoices with amount to pay for each invoice + * @param string $datepaye {@from body} Payment date {@type timestamp} + * @param int $paiementid {@from body} Payment mode Id {@min 1} + * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} + * @param int $accountid {@from body} Account Id {@min 1} + * @param string $num_paiement {@from body} Payment number (optional) + * @param string $comment {@from body} Note (optional) + * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ') + * @param string $chqbank {@from body} Issuer bank name (optional) + * + * @url POST /paymentsdistributed + * + * @return int Payment ID * - * @return int - * - * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 400 - */ - public function postLine($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $request_data = (object) $request_data; - - // Reset fk_parent_line for no child products and special product - if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) { - $request_data->fk_parent_line = 0; - } - - // calculate pa_ht - $marginInfos = getMarginInfos($request_data->subprice, $request_data->remise_percent, $request_data->tva_tx, $request_data->localtax1_tx, $request_data->localtax2_tx, $request_data->fk_fournprice, $request_data->pa_ht); - $pa_ht = $marginInfos[0]; - - $updateRes = $this->invoice->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->date_start, - $request_data->date_end, - $request_data->fk_code_ventilation, - $request_data->info_bits, - $request_data->fk_remise_except, - 'HT', - 0, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $request_data->origin, - $request_data->origin_id, - $request_data->fk_parent_line, - empty($request_data->fk_fournprice) ?null:$request_data->fk_fournprice, - $pa_ht, - $request_data->label, - $request_data->array_options, - $request_data->situation_percent, - $request_data->fk_prev_id, - $request_data->fk_unit, - 0, - $request_data->ref_ext - ); - - if ($updateRes < 0) { - throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error); - } - - return $updateRes; - } - - /** - * Adds a contact to an invoice - * - * @param int $id Order ID - * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link - * @param string $type_contact Type of contact (code). Must a code found into table llx_c_type_contact. For example: BILLING - * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) - * @param int $notrigger Disable all triggers - * - * @url POST {id}/contacts - * - * @return array - * - * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 - * - */ - public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger); - if ($result < 0) { - throw new RestException(500, 'Error : '.$this->invoice->error); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - return $this->_cleanObjectDatas($this->invoice); - } - - - - /** - * Sets an invoice as draft - * - * @param int $id Order ID - * @param int $idwarehouse Warehouse ID - * - * @url POST {id}/settodraft - * - * @return array - * - * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 - * - */ - public function settodraft($id, $idwarehouse = -1) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse); - if ($result == 0) { - throw new RestException(304, 'Nothing done.'); - } - if ($result < 0) { - throw new RestException(500, 'Error : '.$this->invoice->error); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - return $this->_cleanObjectDatas($this->invoice); - } - - - /** - * Validate an invoice - * - * If you get a bad value for param notrigger check that ou provide this in body - * { - * "idwarehouse": 0, - * "notrigger": 0 - * } - * - * @param int $id Invoice ID - * @param int $idwarehouse Warehouse ID - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * - * @url POST {id}/validate - * - * @return array - */ - public function validate($id, $idwarehouse = 0, $notrigger = 0) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger); - if ($result == 0) { - throw new RestException(304, 'Error nothing done. May be object is already validated'); - } - if ($result < 0) { - throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - return $this->_cleanObjectDatas($this->invoice); - } - - /** - * Sets an invoice as paid - * - * @param int $id Order ID - * @param string $close_code Code filled if we classify to 'Paid completely' when payment is not complete (for escompte for example) - * @param string $close_note Comment defined if we classify to 'Paid' when payment is not complete (for escompte for example) - * - * @url POST {id}/settopaid - * - * @return array An invoice object - * - * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 - */ - public function settopaid($id, $close_code = '', $close_note = '') - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->invoice->set_paid(DolibarrApiAccess::$user, $close_code, $close_note); - if ($result == 0) { - throw new RestException(304, 'Error nothing done. May be object is already validated'); - } - if ($result < 0) { - throw new RestException(500, 'Error : '.$this->invoice->error); - } - - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - return $this->_cleanObjectDatas($this->invoice); - } - - - /** - * Sets an invoice as unpaid - * - * @param int $id Order ID - * - * @url POST {id}/settounpaid - * - * @return array An invoice object - * - * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 - */ - public function settounpaid($id) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->invoice->set_unpaid(DolibarrApiAccess::$user); - if ($result == 0) { - throw new RestException(304, 'Nothing done'); - } - if ($result < 0) { - throw new RestException(500, 'Error : '.$this->invoice->error); - } - - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - return $this->_cleanObjectDatas($this->invoice); - } - - /** - * Get discount from invoice - * - * @param int $id Id of invoice - * - * @url GET {id}/discount - * - * @return mixed - */ - public function getDiscount($id) - { - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - - if (!DolibarrApiAccess::$user->rights->facture->lire) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $discountcheck = new DiscountAbsolute($this->db); - $result = $discountcheck->fetch(0, $this->invoice->id); - - if ($result == 0) { - throw new RestException(404, 'Discount not found'); - } - if ($result < 0) { - throw new RestException(500, $discountcheck->error); - } - - return parent::_cleanObjectDatas($discountcheck); - } - - /** - * Create a discount (credit available) for a credit note or a deposit. - * - * @param int $id Invoice ID - * @url POST {id}/markAsCreditAvailable - * - * @return array An invoice object - * - * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 - */ - public function markAsCreditAvailable($id) - { - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - if ($this->invoice->paye) { - throw new RestException(500, 'Alreay paid'); - } - - $this->invoice->fetch($id); - $this->invoice->fetch_thirdparty(); - - // Check if there is already a discount (protection to avoid duplicate creation when resubmit post) - $discountcheck = new DiscountAbsolute($this->db); - $result = $discountcheck->fetch(0, $this->invoice->id); - - $canconvert = 0; - if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) - if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) - if ($canconvert) - { - $this->db->begin(); - - $amount_ht = $amount_tva = $amount_ttc = array(); - $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array(); - - // Loop on each vat rate - $i = 0; - foreach ($this->invoice->lines as $line) - { - if ($line->product_type < 9 && $line->total_ht != 0) // Remove lines with product_type greater than or equal to 9 - { // no need to create discount if amount is null - $amount_ht[$line->tva_tx] += $line->total_ht; - $amount_tva[$line->tva_tx] += $line->total_tva; - $amount_ttc[$line->tva_tx] += $line->total_ttc; - $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht; - $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva; - $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc; - $i++; - } - } - - // Insert one discount by VAT rate category - $discount = new DiscountAbsolute($this->db); - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { - $discount->description = '(CREDIT_NOTE)'; - } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) { - $discount->description = '(DEPOSIT)'; - } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) { - $discount->description = '(EXCESS RECEIVED)'; - } else { - throw new RestException(500, 'Cant convert to reduc an Invoice of this type'); - } - - $discount->fk_soc = $this->invoice->socid; - $discount->fk_facture_source = $this->invoice->id; - - $error = 0; - - if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) - { - // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT - - // Total payments - $sql = 'SELECT SUM(pf.amount) as total_payments'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; - $sql .= ' WHERE pf.fk_facture = '.$this->invoice->id; - $sql .= ' AND pf.fk_paiement = p.rowid'; - $sql .= ' AND p.entity IN ('.getEntity('invoice').')'; - $resql = $this->db->query($sql); - if (!$resql) dol_print_error($this->db); - - $res = $this->db->fetch_object($resql); - $total_payments = $res->total_payments; - - // Total credit note and deposit - $total_creditnote_and_deposit = 0; - $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql .= " re.description, re.fk_facture_source"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re"; - $sql .= " WHERE fk_facture = ".$this->invoice->id; - $resql = $this->db->query($sql); - if (!empty($resql)) { - while ($obj = $this->db->fetch_object($resql)) $total_creditnote_and_deposit += $obj->amount_ttc; - } else dol_print_error($this->db); - - $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc; - $discount->amount_tva = 0; - $discount->tva_tx = 0; - - $result = $discount->create(DolibarrApiAccess::$user); - if ($result < 0) - { - $error++; - } - } - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) - { - foreach ($amount_ht as $tva_tx => $xxx) - { - $discount->amount_ht = abs($amount_ht[$tva_tx]); - $discount->amount_tva = abs($amount_tva[$tva_tx]); - $discount->amount_ttc = abs($amount_ttc[$tva_tx]); - $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]); - $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]); - $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]); - $discount->tva_tx = abs($tva_tx); - - $result = $discount->create(DolibarrApiAccess::$user); - if ($result < 0) - { - $error++; - break; - } - } - } - - if (empty($error)) - { - if ($this->invoice->type != Facture::TYPE_DEPOSIT) { - // Classe facture - $result = $this->invoice->set_paid(DolibarrApiAccess::$user); - if ($result >= 0) - { - $this->db->commit(); - } else { - $this->db->rollback(); - throw new RestException(500, 'Could not set paid'); - } - } else { - $this->db->commit(); - } - } else { - $this->db->rollback(); - throw new RestException(500, 'Discount creation error'); - } - } - - return $this->_cleanObjectDatas($this->invoice); - } - - /** - * Add a discount line into an invoice (as an invoice line) using an existing absolute discount - * - * Note that this consume the discount. - * - * @param int $id Id of invoice - * @param int $discountid Id of discount - * - * @url POST {id}/usediscount/{discountid} - * - * @return int - * - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - */ - public function useDiscount($id, $discountid) - { - - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - if (empty($id)) { - throw new RestException(400, 'Invoice ID is mandatory'); - } - if (empty($discountid)) { - throw new RestException(400, 'Discount ID is mandatory'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - $result = $this->invoice->insert_discount($discountid); - if ($result < 0) { - throw new RestException(405, $this->invoice->error); - } - - return $result; - } - - /** - * Add an available credit note discount to payments of an existing invoice. - * - * Note that this consume the credit note. - * - * @param int $id Id of invoice - * @param int $discountid Id of a discount coming from a credit note - * - * @url POST {id}/usecreditnote/{discountid} - * - * @return int - * - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - */ - public function useCreditNote($id, $discountid) - { - - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - if (empty($id)) { - throw new RestException(400, 'Invoice ID is mandatory'); - } - if (empty($discountid)) { - throw new RestException(400, 'Credit ID is mandatory'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $discount = new DiscountAbsolute($this->db); - $result = $discount->fetch($discountid); - if (!$result) { - throw new RestException(404, 'Credit not found'); - } - - $result = $discount->link_to_invoice(0, $id); - if ($result < 0) { - throw new RestException(405, $discount->error); - } - - return $result; - } - - /** - * Get list of payments of a given invoice - * - * @param int $id Id of invoice - * - * @url GET {id}/payments - * - * @return array - * - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - */ - public function getPayments($id) - { - - if (!DolibarrApiAccess::$user->rights->facture->lire) { - throw new RestException(401); - } - if (empty($id)) { - throw new RestException(400, 'Invoice ID is mandatory'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - $result = $this->invoice->getListOfPayments(); - if ($result < 0) { - throw new RestException(405, $this->invoice->error); - } - - return $result; - } - - - /** - * Add payment line to a specific invoice with the remain to pay as amount. - * - * @param int $id Id of invoice - * @param string $datepaye {@from body} Payment date {@type timestamp} - * @param int $paymentid {@from body} Payment mode Id {@min 1} - * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} - * @param int $accountid {@from body} Account Id {@min 1} - * @param string $num_payment {@from body} Payment number (optional) - * @param string $comment {@from body} Note private (optional) - * @param string $chqemetteur {@from body} Payment issuer (mandatory if paymentcode = 'CHQ') - * @param string $chqbank {@from body} Issuer bank name (optional) - * - * @url POST {id}/payments - * - * @return int Payment ID - * - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - */ - public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '') - { - global $conf; - - require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; - - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(403); - } - if (empty($id)) { - throw new RestException(400, 'Invoice ID is mandatory'); - } - - if (!DolibarrApi::_checkAccessToResource('facture', $id)) { - throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - if (!empty($conf->banque->enabled)) { - if (empty($accountid)) { - throw new RestException(400, 'Account ID is mandatory'); - } - } - - if (empty($paymentid)) { - throw new RestException(400, 'Payment ID or Payment Code is mandatory'); - } - - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - // Calculate amount to pay - $totalpaye = $this->invoice->getSommePaiement(); - $totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); - $totaldeposits = $this->invoice->getSumDepositsUsed(); - $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); - - $this->db->begin(); - - $amounts = array(); - $multicurrency_amounts = array(); - - // Clean parameters amount if payment is for a credit note - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { - $resteapayer = price2num($resteapayer, 'MT'); - $amounts[$id] = -$resteapayer; - // Multicurrency - $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); - $multicurrency_amounts[$id] = -$newvalue; - } else { - $resteapayer = price2num($resteapayer, 'MT'); - $amounts[$id] = $resteapayer; - // Multicurrency - $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); - $multicurrency_amounts[$id] = $newvalue; - } - - - // Creation of payment line - $paymentobj = new Paiement($this->db); - $paymentobj->datepaye = $datepaye; - $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id - $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching - $paymentobj->paiementid = $paymentid; - $paymentobj->paiementcode = dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1); - $paymentobj->num_payment = $num_payment; - $paymentobj->note_private = $comment; - - $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices - if ($payment_id < 0) - { - $this->db->rollback(); - throw new RestException(400, 'Payment error : '.$paymentobj->error); - } - - if (!empty($conf->banque->enabled)) { - $label = '(CustomerInvoicePayment)'; - - if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) { - throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode); - } - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note - $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank); - if ($result < 0) - { - $this->db->rollback(); - throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error); - } - } - - $this->db->commit(); - - return $payment_id; - } - - /** - * Add a payment to pay partially or completely one or several invoices. - * Warning: Take care that all invoices are owned by the same customer. - * Example of value for parameter arrayofamounts: {"1": {"amount": "99.99", "multicurrency_amount": ""}, "2": {"amount": "", "multicurrency_amount": "10"}} - * - * @param array $arrayofamounts {@from body} Array with id of invoices with amount to pay for each invoice - * @param string $datepaye {@from body} Payment date {@type timestamp} - * @param int $paymentid {@from body} Payment mode Id {@min 1} - * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} - * @param int $accountid {@from body} Account Id {@min 1} - * @param string $num_payment {@from body} Payment number (optional) - * @param string $comment {@from body} Note private (optional) - * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ') - * @param string $chqbank {@from body} Issuer bank name (optional) - * @param string $ref_ext {@from body} External reference (optional) - * @param bool $accepthigherpayment {@from body} Accept higher payments that it remains to be paid (optional) - * - * @url POST /paymentsdistributed - * - * @return int Payment ID - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false) - { - global $conf; - - require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; - - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(403); - } - foreach ($arrayofamounts as $id => $amount) { - if (empty($id)) { - throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}'); - } - if (!DolibarrApi::_checkAccessToResource('facture', $id)) { - throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login); - } - } - - if (!empty($conf->banque->enabled)) { - if (empty($accountid)) { - throw new RestException(400, 'Account ID is mandatory'); - } - } - if (empty($paymentid)) { - throw new RestException(400, 'Payment ID or Payment Code is mandatory'); - } - - $this->db->begin(); - - $amounts = array(); - $multicurrency_amounts = array(); - - // Loop on each invoice to pay - foreach ($arrayofamounts as $id => $amountarray) - { - $result = $this->invoice->fetch($id); - if (!$result) { - $this->db->rollback(); - throw new RestException(404, 'Invoice ID '.$id.' not found'); - } - - if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) { - $this->db->rollback(); - throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')'); - } - - $is_multicurrency = 0; - $total_ttc = $this->invoice->total_ttc; - - if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") { - $is_multicurrency = 1; - $total_ttc = $this->invoice->multicurrency_total_ttc; - } - - // Calculate amount to pay - $totalpaye = $this->invoice->getSommePaiement($is_multicurrency); - $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency); - $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency); - $remainstopay = $amount = price2num($total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); - - if (!$is_multicurrency && $amountarray["amount"] != 'remain') - { - $amount = price2num($amountarray["amount"], 'MT'); - } - - if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') - { - $amount = price2num($amountarray["multicurrency_amount"], 'MT'); - } - - if ($amount > $remainstopay && !$accepthigherpayment) { - $this->db->rollback(); - throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')'); - } - - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { - $amount = -$amount; - } - - if ($is_multicurrency) { - $amounts[$id] = null; - // Multicurrency - $multicurrency_amounts[$id] = $amount; - } else { - $amounts[$id] = $amount; - // Multicurrency - $multicurrency_amounts[$id] = null; - } - } - - // Creation of payment line - $paymentobj = new Paiement($this->db); - $paymentobj->datepaye = $datepaye; - $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id - $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching - $paymentobj->paiementid = $paymentid; - $paymentobj->paiementcode = dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1); - $paymentobj->num_payment = $num_payment; - $paymentobj->note_private = $comment; - $paymentobj->ref_ext = $ref_ext; - $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices - if ($payment_id < 0) - { - $this->db->rollback(); - throw new RestException(400, 'Payment error : '.$paymentobj->error); - } - if (!empty($conf->banque->enabled)) { - $label = '(CustomerInvoicePayment)'; - if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) { - throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode); - } - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note - $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank); - if ($result < 0) - { - $this->db->rollback(); - throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error); - } - } - - $this->db->commit(); - - return $payment_id; - } - - /** - * Update a payment - * - * @param int $id Id of payment - * @param string $num_payment Payment number - * - * @url PUT payments/{id} - * - * @return array - * @throws RestException 400 Bad parameters - * @throws RestException 401 Not allowed - * @throws RestException 404 Not found - */ - public function putPayment($id, $num_payment = '') - { - require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; - - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - if (empty($id)) { - throw new RestException(400, 'Payment ID is mandatory'); - } - - $paymentobj = new Paiement($this->db); - $result = $paymentobj->fetch($id); - - if (!$result) { - throw new RestException(404, 'Payment not found'); - } - - if (!empty($num_payment)) { - $result = $paymentobj->update_num($num_payment); - if ($result < 0) { - throw new RestException(500, 'Error when updating the payment num'); - } - } - - return [ - 'success' => [ - 'code' => 200, - 'message' => 'Payment updated' - ] - ]; - } - - // 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->note); - unset($object->address); - unset($object->barcode_type); - unset($object->barcode_type_code); - unset($object->barcode_type_label); - unset($object->barcode_type_coder); - - return $object; - } - - /** - * Validate fields before create or update object - * - * @param array|null $data Datas to validate - * @return array - * - * @throws RestException - */ - private function _validate($data) - { - $invoice = array(); - foreach (Invoices::$FIELDS as $field) { - if (!isset($data[$field])) { - throw new RestException(400, "$field field missing"); - } - $invoice[$field] = $data[$field]; - } - return $invoice; - } + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function addPaymentDistributed($arrayofamounts, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement = '', $comment = '', $chqemetteur = '', $chqbank = '') + { + global $conf; + + require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; + + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(403); + } + foreach ($arrayofamounts as $id => $amount) { + if (empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}'); + } + if (!DolibarrApi::_checkAccessToResource('facture', $id)) { + throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login); + } + } + + if (!empty($conf->banque->enabled)) { + if (empty($accountid)) { + throw new RestException(400, 'Account ID is mandatory'); + } + } + if (empty($paiementid)) { + throw new RestException(400, 'Paiement ID or Paiement Code is mandatory'); + } + + $this->db->begin(); + + $amounts = array(); + $multicurrency_amounts = array(); + + // Loop on each invoice to pay + foreach ($arrayofamounts as $id => $amount) + { + $result = $this->invoice->fetch($id); + if (!$result) { + $this->db->rollback(); + throw new RestException(404, 'Invoice ID '.$id.' not found'); + } + + // Calculate amount to pay + $totalpaye = $this->invoice->getSommePaiement(); + $totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); + $totaldeposits = $this->invoice->getSumDepositsUsed(); + $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); + if ($amount != 'remain') + { + if ($amount > $resteapayer) + { + $this->db->rollback(); + throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$resteapayer.')'); + } + $resteapayer = $amount; + } + // Clean parameters amount if payment is for a credit note + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { + $resteapayer = price2num($resteapayer, 'MT'); + $amounts[$id] = -$resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); + $multicurrency_amounts[$id] = -$newvalue; + } else { + $resteapayer = price2num($resteapayer, 'MT'); + $amounts[$id] = $resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); + $multicurrency_amounts[$id] = $newvalue; + } + } + + // Creation of payment line + $paiement = new Paiement($this->db); + $paiement->datepaye = $datepaye; + $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id + $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching + $paiement->paiementid = $paiementid; + $paiement->paiementcode = dol_getIdFromCode($this->db, $paiementid, 'c_paiement', 'id', 'code', 1); + $paiement->num_paiement = $num_paiement; + $paiement->note = $comment; + $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices + if ($paiement_id < 0) + { + $this->db->rollback(); + throw new RestException(400, 'Payment error : '.$paiement->error); + } + if (!empty($conf->banque->enabled)) { + $label = '(CustomerInvoicePayment)'; + if ($paiement->paiementcode == 'CHQ' && empty($chqemetteur)) { + throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paiement->paiementcode); + } + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note + $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank); + if ($result < 0) + { + $this->db->rollback(); + throw new RestException(400, 'Add payment to bank error : '.$paiement->error); + } + } + + $this->db->commit(); + + return $paiement_id; + } + + // 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->note); + unset($object->address); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); + + return $object; + } + + /** + * Validate fields before create or update object + * + * @param array|null $data Datas to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $invoice = array(); + foreach (Invoices::$FIELDS as $field) { + if (!isset($data[$field])) { + throw new RestException(400, "$field field missing"); + } + $invoice[$field] = $data[$field]; + } + return $invoice; + } } --- /tmp/dsg/dolibarr/htdocs/compta/facture/class/github_facture-rec.class.php +++ /tmp/dsg/dolibarr/htdocs/compta/facture/class/client_facture-rec.class.php @@ -50,12 +50,12 @@ public $table_element = 'facture_rec'; /** - * @var string Name of subtable line + * @var int Name of subtable line */ public $table_element_line = 'facturedet_rec'; /** - * @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 */ public $fk_element = 'fk_facture'; @@ -73,11 +73,6 @@ * {@inheritdoc} */ protected $table_ref_field = 'titre'; - - /** - * @var string The label of recurring invoice - */ - public $title; public $number; public $date; @@ -97,7 +92,7 @@ */ public $frequency; - /** + /** * @var string Unit frequency */ public $unit_frequency; @@ -160,7 +155,7 @@ 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105), 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110), 'modelpdf' =>array('type'=>'varchar(255)', 'label'=>'Modelpdf', 'enabled'=>1, 'visible'=>-1, 'position'=>115), - 'date_last_gen' =>array('type'=>'varchar(7)', 'label'=>'Last gen', 'enabled'=>1, 'visible'=>-1, 'position'=>120), + 'last_gen' =>array('type'=>'varchar(7)', 'label'=>'Last gen', 'enabled'=>1, 'visible'=>-1, 'position'=>120), 'unit_frequency' =>array('type'=>'varchar(2)', 'label'=>'Unit frequency', 'enabled'=>1, 'visible'=>-1, 'position'=>125), 'date_when' =>array('type'=>'datetime', 'label'=>'Date when', 'enabled'=>1, 'visible'=>-1, 'position'=>130), 'date_last_gen' =>array('type'=>'datetime', 'label'=>'Date last gen', 'enabled'=>1, 'visible'=>-1, 'position'=>135), @@ -204,10 +199,9 @@ * * @param User $user User object * @param int $facid Id of source invoice - * @param int $notrigger No trigger * @return int <0 if KO, id of invoice created if OK */ - public function create($user, $facid, $notrigger = 0) + public function create($user, $facid) { global $conf; @@ -215,7 +209,7 @@ $now = dol_now(); // Clean parameters - $this->titre = trim(isset($this->titre) ? $this->titre : $this->title); // deprecated + $this->titre = trim($this->titre); // deprecated $this->title = trim($this->title); $this->usenewprice = empty($this->usenewprice) ? 0 : $this->usenewprice; if (empty($this->suspended)) $this->suspended = 0; @@ -226,6 +220,7 @@ $this->frequency = 0; $this->date_when = null; } + $this->frequency = abs($this->frequency); $this->nb_gen_done = 0; @@ -282,8 +277,8 @@ $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL"); $sql .= ", ".(!empty($this->modelpdf) ? ("'".$this->db->escape($this->modelpdf)."'") : "NULL"); $sql .= ", '".$this->db->escape($user->id)."'"; - $sql .= ", ".(!empty($facsrc->fk_project) ? "'".$this->db->escape($facsrc->fk_project)."'" : "null"); - $sql .= ", ".(!empty($facsrc->fk_account) ? "'".$this->db->escape($facsrc->fk_account)."'" : "null"); + $sql .= ", ".(!empty($facsrc->fk_project) ? "'".$facsrc->fk_project."'" : "null"); + $sql .= ", ".(!empty($facsrc->fk_account) ? "'".$facsrc->fk_account."'" : "null"); $sql .= ", ".($facsrc->cond_reglement_id > 0 ? $this->db->escape($facsrc->cond_reglement_id) : "null"); $sql .= ", ".($facsrc->mode_reglement_id > 0 ? $this->db->escape($facsrc->mode_reglement_id) : "null"); $sql .= ", ".$this->usenewprice; @@ -317,53 +312,47 @@ $tva_tx = $facsrc->lines[$i]->tva_tx; if (!empty($facsrc->lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$facsrc->lines[$i]->vat_src_code.')'; - $result_insert = $this->addline( - $facsrc->lines[$i]->desc, - $facsrc->lines[$i]->subprice, - $facsrc->lines[$i]->qty, + $result_insert = $this->addline( + $facsrc->lines[$i]->desc, + $facsrc->lines[$i]->subprice, + $facsrc->lines[$i]->qty, $tva_tx, - $facsrc->lines[$i]->localtax1_tx, - $facsrc->lines[$i]->localtax2_tx, - $facsrc->lines[$i]->fk_product, - $facsrc->lines[$i]->remise_percent, - 'HT', + $facsrc->lines[$i]->localtax1_tx, + $facsrc->lines[$i]->localtax2_tx, + $facsrc->lines[$i]->fk_product, + $facsrc->lines[$i]->remise_percent, + 'HT', $facsrc->lines[$i]->info_bits, - '', - 0, - $facsrc->lines[$i]->product_type, - $facsrc->lines[$i]->rang, - $facsrc->lines[$i]->special_code, - $facsrc->lines[$i]->label, + '', + 0, + $facsrc->lines[$i]->product_type, + $facsrc->lines[$i]->rang, + $facsrc->lines[$i]->special_code, + $facsrc->lines[$i]->label, $facsrc->lines[$i]->fk_unit, - $facsrc->lines[$i]->multicurrency_subprice, - 0, - 0, - null, - $facsrc->lines[$i]->pa_ht - ); + $facsrc->lines[$i]->multicurrency_subprice + ); if ($result_insert < 0) { $error++; - } else { - $objectline = new FactureLigneRec($this->db); - $result2 = $objectline->fetch($result_insert); - if ($result2 > 0) { - // Extrafields - if (method_exists($facsrc->lines[$i], 'fetch_optionals')) { - $facsrc->lines[$i]->fetch_optionals($facsrc->lines[$i]->rowid); - $objectline->array_options = $facsrc->lines[$i]->array_options; - } - - $result = $objectline->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } elseif ($result2 < 0) { - $this->errors[] = $objectline->error; - $error++; - } + } + else { + $objectline = new FactureLigneRec($this->db); + if ($objectline->fetch($result_insert)) + { + // Extrafields + if (method_exists($facsrc->lines[$i], 'fetch_optionals')) { + $facsrc->lines[$i]->fetch_optionals($facsrc->lines[$i]->rowid); + $objectline->array_options = $facsrc->lines[$i]->array_options; + } + + $result = $objectline->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } } } @@ -373,68 +362,54 @@ } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) + if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) { foreach ($this->linked_objects as $origin => $tmp_origin_id) { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { - $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { - $this->error = $this->db->lasterror(); - $error++; - } - } - } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) - { - $origin_id = $tmp_origin_id; - $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { - $this->error = $this->db->lasterror(); - $error++; - } - } + if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + { + foreach ($tmp_origin_id as $origin_id) + { + $ret = $this->add_object_linked($origin, $origin_id); + if (!$ret) + { + $this->error = $this->db->lasterror(); + $error++; + } + } + } + else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) + { + $origin_id = $tmp_origin_id; + $ret = $this->add_object_linked($origin, $origin_id); + if (!$ret) + { + $this->error = $this->db->lasterror(); + $error++; + } + } } - } - - if (!$error) { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('BILLREC_CREATE', $user); - if ($result < 0) - { - $this->db->rollback(); - return -2; - } - // End call triggers } if ($error) { $this->db->rollback(); - return -3; - } else { + } + else + { $this->db->commit(); return $this->id; } - } else { - $this->error = $this->db->lasterror(); + } + else + { + $this->error = $this->db->lasterror(); $this->db->rollback(); return -2; } - } else { + } + else + { $this->db->rollback(); return -1; } @@ -450,46 +425,48 @@ */ public function update(User $user, $notrigger = 0) { - global $conf; - - $error = 0; - - $sql = "UPDATE ".MAIN_DB_PREFIX."facture_rec SET"; - $sql .= " fk_soc = ".$this->fk_soc; - // TODO Add missing fields - $sql .= " WHERE rowid = ".$this->id; - - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('BILLREC_UPDATE', $user); - if ($result < 0) - { - $this->db->rollback(); - return -2; - } - // End call triggers - } - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -2; - } + global $conf; + + $error = 0; + + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_rec SET"; + $sql .= " fk_soc = ".$this->fk_soc; + // TODO Add missing fields + $sql .= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('BILLREC_UPDATE', $user); + if ($result < 0) + { + $this->db->rollback(); + return -2; + } + // End call triggers + } + $this->db->commit(); + return 1; + } + else + { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -2; + } } /** @@ -506,13 +483,13 @@ $sql .= ', f.remise_percent, f.remise_absolue, f.remise'; $sql .= ', f.date_lim_reglement as dlr'; $sql .= ', f.note_private, f.note_public, f.fk_user_author'; - $sql .= ', f.modelpdf as model_pdf'; + $sql .= ', f.modelpdf'; $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project'; $sql .= ', f.fk_account'; $sql .= ', f.frequency, f.unit_frequency, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.usenewprice, f.auto_validate'; - $sql .= ', f.generate_pdf'; - $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc"; - $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; + $sql .= ', f.generate_pdf'; + $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc"; + $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc'; //$sql.= ', el.fk_source'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f'; @@ -520,15 +497,12 @@ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'"; $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; - if ($rowid) { - $sql .= ' AND f.rowid='.((int) $rowid); - } elseif ($ref) { - $sql .= " AND f.titre='".$this->db->escape($ref)."'"; - // This field are not used for template invoice - //} elseif ($ref_ext) { $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'"; } - } else { - $sql .= ' AND f.rowid = 0'; - } + if ($rowid) $sql .= ' AND f.rowid='.$rowid; + elseif ($ref) $sql .= " AND f.titre='".$this->db->escape($ref)."'"; + /* This field are not used for template invoice + if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'"; + if ($ref_int) $sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'"; + */ $result = $this->db->query($sql); if ($result) @@ -573,8 +547,7 @@ $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; $this->user_author = $obj->fk_user_author; - $this->modelpdf = $obj->model_pdf; // deprecatd - $this->model_pdf = $obj->model_pdf; + $this->modelpdf = $obj->modelpdf; $this->rang = $obj->rang; $this->special_code = $obj->special_code; $this->frequency = $obj->frequency; @@ -597,7 +570,7 @@ if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; - // Retrieve all extrafield + // Retreive all extrafield // fetch optionals attributes and labels $this->fetch_optionals(); @@ -611,12 +584,16 @@ return -3; } return 1; - } else { + } + else + { $this->error = 'Bill with id '.$rowid.' or ref '.$ref.' not found sql='.$sql; dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR); return -2; } - } else { + } + else + { $this->error = $this->db->error(); return -1; } @@ -630,24 +607,24 @@ */ public function getLinesArray() { - return $this->fetch_lines(); + return $this->fetch_lines(); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Get lines of template invoices into this->lines * * @return int 1 if OK, < 0 if KO - */ + */ public function fetch_lines() { global $extrafields; - // phpcs:enable + // phpcs:enable $this->lines = array(); - // Retrieve all extrafield for line + // Retreive all extrafield for line // fetch optionals attributes and labels if (!is_object($extrafields)) { @@ -658,11 +635,11 @@ $sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx, '; $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; - $sql .= ' l.info_bits, l.date_start_fill, l.date_end_fill, l.total_ht, l.total_tva, l.total_ttc, l.fk_product_fournisseur_price, l.buy_price_ht as pa_ht,'; + $sql .= ' l.info_bits, l.date_start_fill, l.date_end_fill, l.total_ht, l.total_tva, l.total_ttc, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,'; //$sql.= ' l.situation_percent, l.fk_prev_id,'; //$sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,'; $sql .= ' l.rang, l.special_code,'; - //$sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_product_fournisseur_price, l.buy_price_ht as pa_ht,'; + //$sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,'; $sql .= ' l.fk_unit, l.fk_contract_line,'; $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,'; $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc'; @@ -713,22 +690,16 @@ $line->total_ht = $objp->total_ht; $line->total_tva = $objp->total_tva; $line->total_ttc = $objp->total_ttc; - - //$line->code_ventilation = $objp->fk_code_ventilation; - - $line->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price; - $line->fk_fournprice = $objp->fk_product_fournisseur_price; // For backward compatibility - - $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_product_fournisseur_price, $objp->pa_ht); - - $line->buyprice = $marginInfos[0]; - $line->pa_ht = $marginInfos[0]; // For backward compatibility + $line->code_ventilation = $objp->fk_code_ventilation; + $line->fk_fournprice = $objp->fk_fournprice; + $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); + $line->pa_ht = $marginInfos[0]; $line->marge_tx = $marginInfos[1]; $line->marque_tx = $marginInfos[2]; $line->rang = $objp->rang; $line->special_code = $objp->special_code; $line->fk_unit = $objp->fk_unit; - $line->fk_contract_line = $objp->fk_contract_line; + $line->fk_contract_line = $objp->fk_contract_line; // Ne plus utiliser $line->price = $objp->price; @@ -751,7 +722,9 @@ $this->db->free($result); return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); return -3; } @@ -768,17 +741,17 @@ */ public function delete(User $user, $notrigger = 0, $idwarehouse = -1) { - $rowid = $this->id; - - dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); - - $error = 0; + $rowid = $this->id; + + dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); + + $error = 0; $this->db->begin(); $main = MAIN_DB_PREFIX.'facturedet_rec'; - $ef = $main."_extrafields"; - $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture = $rowid)"; - dol_syslog($sqlef); + $ef = $main."_extrafields"; + $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture = $rowid)"; + dol_syslog($sqlef); $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet_rec WHERE fk_facture = ".$rowid; dol_syslog($sql); if ($this->db->query($sqlef) && $this->db->query($sql)) @@ -791,24 +764,30 @@ $res = $this->deleteObjectLinked(); if ($res < 0) $error = -3; // Delete extrafields - $res = $this->deleteExtraFields(); - if ($res < 0) $error = -4; - } else { + $res = $this->deleteExtraFields(); + if ($res < 0) $error = -4; + } + else + { $this->error = $this->db->lasterror(); $error = -1; } - } else { + } + else + { $this->error = $this->db->lasterror(); $error = -2; } if (!$error) { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return $error; + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return $error; } } @@ -816,33 +795,33 @@ /** * Add a line to invoice * - * @param string $desc Description de la ligne - * @param double $pu_ht Prix unitaire HT (> 0 even for credit note) - * @param double $qty Quantite - * @param double $txtva Taux de tva force, sinon -1 + * @param string $desc Description de la ligne + * @param double $pu_ht Prix unitaire HT (> 0 even for credit note) + * @param double $qty Quantite + * @param double $txtva Taux de tva force, sinon -1 * @param double $txlocaltax1 Local tax 1 rate (deprecated) * @param double $txlocaltax2 Local tax 2 rate (deprecated) - * @param int $fk_product Product/Service ID predefined - * @param double $remise_percent Percentage discount of the line - * @param string $price_base_type HT or TTC - * @param int $info_bits VAT npr or not ? - * @param int $fk_remise_except Id remise - * @param double $pu_ttc Prix unitaire TTC (> 0 even for credit note) - * @param int $type Type of line (0=product, 1=service) - * @param int $rang Position of line - * @param int $special_code Special code - * @param string $label Label of the line - * @param string $fk_unit Unit + * @param int $fk_product Product/Service ID predefined + * @param double $remise_percent Percentage discount of the line + * @param string $price_base_type HT or TTC + * @param int $info_bits VAT npr or not ? + * @param int $fk_remise_except Id remise + * @param double $pu_ttc Prix unitaire TTC (> 0 even for credit note) + * @param int $type Type of line (0=product, 1=service) + * @param int $rang Position of line + * @param int $special_code Special code + * @param string $label Label of the line + * @param string $fk_unit Unit * @param double $pu_ht_devise Unit price in currency * @param int $date_start_fill 1=Flag to fill start date when generating invoice * @param int $date_end_fill 1=Flag to fill end date when generating invoice * @param int $fk_fournprice Supplier price id (to calculate margin) or '' * @param int $pa_ht Buying price of line (to calculate margin) or '' - * @return int <0 if KO, Id of line if OK + * @return int <0 if KO, Id of line if OK */ public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $rang = -1, $special_code = 0, $label = '', $fk_unit = null, $pu_ht_devise = 0, $date_start_fill = 0, $date_end_fill = 0, $fk_fournprice = null, $pa_ht = 0) { - global $mysoc; + global $mysoc; $facid = $this->id; @@ -870,9 +849,7 @@ $qty = price2num($qty); $pu_ht = price2num($pu_ht); $pu_ttc = price2num($pu_ttc); - if (!preg_match('/\((.*)\)/', $txtva)) { - $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' - } + $txtva = price2num($txtva); $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); if (empty($txtva)) $txtva = 0; @@ -883,7 +860,9 @@ if ($price_base_type == 'HT') { $pu = $pu_ht; - } else { + } + else + { $pu = $pu_ttc; } @@ -946,7 +925,7 @@ $sql .= ", fk_unit"; $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; $sql .= ") VALUES ("; - $sql .= " ".((int) $facid); + $sql .= "'".$facid."'"; $sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null"); $sql .= ", '".$this->db->escape($desc)."'"; $sql .= ", ".price2num($pu_ht); @@ -954,10 +933,10 @@ $sql .= ", ".price2num($txtva); $sql .= ", '".$this->db->escape($vat_src_code)."'"; $sql .= ", ".price2num($txlocaltax1); - $sql .= ", '".$this->db->escape(isset($localtaxes_type[0]) ? $localtaxes_type[0] : '')."'"; + $sql .= ", '".$this->db->escape($localtaxes_type[0])."'"; $sql .= ", ".price2num($txlocaltax2); - $sql .= ", '".$this->db->escape(isset($localtaxes_type[2]) ? $localtaxes_type[2] : '')."'"; - $sql .= ", ".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null"); + $sql .= ", '".$this->db->escape($localtaxes_type[2])."'"; + $sql .= ", ".(!empty($fk_product) ? "'".$fk_product."'" : "null"); $sql .= ", ".$product_type; $sql .= ", ".price2num($remise_percent); $sql .= ", ".price2num($pu_ht); @@ -990,7 +969,9 @@ $this->id = $facid; $this->update_price(); return $lineId; - } else { + } + else + { $this->error = $this->db->lasterror(); return -1; } @@ -1028,134 +1009,135 @@ */ public function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $rang = -1, $special_code = 0, $label = '', $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $date_start_fill = 0, $date_end_fill = 0, $fk_fournprice = null, $pa_ht = 0) { - global $mysoc; - - $facid = $this->id; - - dol_syslog(get_class($this)."::updateline facid=".$facid." rowid=$rowid, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, type=$type, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG); - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - - // Clean parameters - if (empty($remise_percent)) $remise_percent = 0; - - // Check parameters - if ($type < 0) return -1; - - if ($this->brouillon) - { - // Clean parameters - $remise_percent = price2num($remise_percent); - $qty = price2num($qty); - if (empty($info_bits)) $info_bits = 0; - $pu_ht = price2num($pu_ht); - $pu_ttc = price2num($pu_ttc); - $pu_ht_devise = price2num($pu_ht_devise); - if (!preg_match('/\((.*)\)/', $txtva)) { - $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' + global $mysoc; + + $facid = $this->id; + + dol_syslog(get_class($this)."::updateline facid=".$facid." rowid=$rowid, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, type=$type, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG); + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + + // Clean parameters + if (empty($remise_percent)) $remise_percent = 0; + + // Check parameters + if ($type < 0) return -1; + + if ($this->brouillon) + { + // Clean parameters + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); + if (empty($info_bits)) $info_bits = 0; + $pu_ht = price2num($pu_ht); + $pu_ttc = price2num($pu_ttc); + $pu_ht_devise = price2num($pu_ht_devise); + $txtva = price2num($txtva); + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); + if (empty($txlocaltax1)) $txlocaltax1 = 0; + if (empty($txlocaltax2)) $txlocaltax2 = 0; + + if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0; + if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0; + if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0; + if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0; + + if ($price_base_type == 'HT') + { + $pu = $pu_ht; } - $txlocaltax1 = price2num($txlocaltax1); - $txlocaltax2 = price2num($txlocaltax2); - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; - - if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0; - if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0; - if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0; - if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0; - - if ($price_base_type == 'HT') - { - $pu = $pu_ht; - } else { - $pu = $pu_ttc; - } - - // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - - $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); - - // Clean vat code - $vat_src_code = ''; - $reg = array(); - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } - - $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); - - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - $total_localtax1 = $tabprice[9]; - $total_localtax2 = $tabprice[10]; - $pu_ht = $tabprice[3]; - $pu_tva = $tabprice[4]; - $pu_ttc = $tabprice[5]; - - // MultiCurrency - $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; - $pu_ht_devise = $tabprice[19]; - - $product_type = $type; - if ($fk_product) - { - $product = new Product($this->db); - $result = $product->fetch($fk_product); - $product_type = $product->type; - } - - $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET "; - $sql .= "fk_facture = ".((int) $facid); - $sql .= ", label=".(!empty($label) ? "'".$this->db->escape($label)."'" : "null"); - $sql .= ", description='".$this->db->escape($desc)."'"; - $sql .= ", price=".price2num($pu_ht); - $sql .= ", qty=".price2num($qty); - $sql .= ", tva_tx=".price2num($txtva); - $sql .= ", vat_src_code='".$this->db->escape($vat_src_code)."'"; - $sql .= ", localtax1_tx=".$txlocaltax1; - $sql .= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'"; - $sql .= ", localtax2_tx=".$txlocaltax2; - $sql .= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'"; - $sql .= ", fk_product=".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null"); - $sql .= ", product_type=".$product_type; - $sql .= ", remise_percent='".price2num($remise_percent)."'"; - $sql .= ", subprice='".price2num($pu_ht)."'"; - $sql .= ", total_ht='".price2num($total_ht)."'"; - $sql .= ", total_tva='".price2num($total_tva)."'"; - $sql .= ", total_localtax1='".price2num($total_localtax1)."'"; - $sql .= ", total_localtax2='".price2num($total_localtax2)."'"; - $sql .= ", total_ttc='".price2num($total_ttc)."'"; - $sql .= ", date_start_fill=".((int) $date_start_fill); - $sql .= ", date_end_fill=".((int) $date_end_fill); - $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : 'null'); - $sql .= ", buy_price_ht=".($pa_ht ? price2num($pa_ht) : 0); - $sql .= ", info_bits=".$info_bits; - $sql .= ", rang=".$rang; - $sql .= ", special_code=".$special_code; - $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null"); - $sql .= ', multicurrency_subprice = '.$pu_ht_devise; - $sql .= ', multicurrency_total_ht = '.$multicurrency_total_ht; - $sql .= ', multicurrency_total_tva = '.$multicurrency_total_tva; - $sql .= ', multicurrency_total_ttc = '.$multicurrency_total_ttc; - $sql .= " WHERE rowid = ".$rowid; - - dol_syslog(get_class($this)."::updateline", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->id = $facid; - $this->update_price(); - return 1; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } + else + { + $pu = $pu_ttc; + } + + // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); + + // Clean vat code + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } + + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + $total_localtax1 = $tabprice[9]; + $total_localtax2 = $tabprice[10]; + $pu_ht = $tabprice[3]; + $pu_tva = $tabprice[4]; + $pu_ttc = $tabprice[5]; + + // MultiCurrency + $multicurrency_total_ht = $tabprice[16]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; + $pu_ht_devise = $tabprice[19]; + + $product_type = $type; + if ($fk_product) + { + $product = new Product($this->db); + $result = $product->fetch($fk_product); + $product_type = $product->type; + } + + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET "; + $sql .= "fk_facture = '".$facid."'"; + $sql .= ", label=".(!empty($label) ? "'".$this->db->escape($label)."'" : "null"); + $sql .= ", description='".$this->db->escape($desc)."'"; + $sql .= ", price=".price2num($pu_ht); + $sql .= ", qty=".price2num($qty); + $sql .= ", tva_tx=".price2num($txtva); + $sql .= ", vat_src_code='".$this->db->escape($vat_src_code)."'"; + $sql .= ", localtax1_tx=".$txlocaltax1; + $sql .= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'"; + $sql .= ", localtax2_tx=".$txlocaltax2; + $sql .= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'"; + $sql .= ", fk_product=".(!empty($fk_product) ? "'".$fk_product."'" : "null"); + $sql .= ", product_type=".$product_type; + $sql .= ", remise_percent='".price2num($remise_percent)."'"; + $sql .= ", subprice='".price2num($pu_ht)."'"; + $sql .= ", total_ht='".price2num($total_ht)."'"; + $sql .= ", total_tva='".price2num($total_tva)."'"; + $sql .= ", total_localtax1='".price2num($total_localtax1)."'"; + $sql .= ", total_localtax2='".price2num($total_localtax2)."'"; + $sql .= ", total_ttc='".price2num($total_ttc)."'"; + $sql .= ", date_start_fill=".((int) $date_start_fill); + $sql .= ", date_end_fill=".((int) $date_end_fill); + $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : 'null'); + $sql .= ", buy_price_ht=".($pa_ht ? price2num($pa_ht) : 0); + $sql .= ", info_bits=".$info_bits; + $sql .= ", rang=".$rang; + $sql .= ", special_code=".$special_code; + $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null"); + $sql .= ', multicurrency_subprice = '.$pu_ht_devise; + $sql .= ', multicurrency_total_ht = '.$multicurrency_total_ht; + $sql .= ', multicurrency_total_tva = '.$multicurrency_total_tva; + $sql .= ', multicurrency_total_ttc = '.$multicurrency_total_ttc; + $sql .= " WHERE rowid = ".$rowid; + + dol_syslog(get_class($this)."::updateline", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->id = $facid; + $this->update_price(); + return 1; + } + else + { + $this->error = $this->db->lasterror(); + return -1; + } + } } @@ -1222,13 +1204,13 @@ $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture_rec'; $sql .= ' WHERE frequency > 0'; // A recurring invoice is an invoice with a frequency - $sql .= " AND (date_when IS NULL OR date_when <= '".$this->db->idate($today)."')"; + $sql .= " AND (date_when IS NULL OR date_when <= '".$db->idate($today)."')"; $sql .= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)'; $sql .= ' AND suspended = 0'; $sql .= ' AND entity = '.$conf->entity; // MUST STAY = $conf->entity here if ($restrictioninvoiceid > 0) $sql .= ' AND rowid = '.$restrictioninvoiceid; - $sql .= $this->db->order('entity', 'ASC'); + $sql .= $db->order('entity', 'ASC'); //print $sql;exit; $parameters = array( 'restrictioninvoiceid' => $restrictioninvoiceid, @@ -1236,28 +1218,29 @@ ); $reshook = $hookmanager->executeHooks('beforeCreationOfRecurringInvoices', $parameters, $sql); // note that $sql might be modified by hooks - $resql = $this->db->query($sql); + $resql = $db->query($sql); if ($resql) { $i = 0; - $num = $this->db->num_rows($resql); + $num = $db->num_rows($resql); if ($num) $this->output .= $langs->trans("FoundXQualifiedRecurringInvoiceTemplate", $num)."\n"; - else $this->output .= $langs->trans("NoQualifiedRecurringInvoiceTemplateFound"); + else + $this->output .= $langs->trans("NoQualifiedRecurringInvoiceTemplateFound"); $saventity = $conf->entity; while ($i < $num) // Loop on each template invoice. If $num = 0, test is false at first pass. { - $line = $this->db->fetch_object($resql); - - $this->db->begin(); + $line = $db->fetch_object($resql); + + $db->begin(); $invoiceidgenerated = 0; $facture = null; - $facturerec = new FactureRec($this->db); + $facturerec = new FactureRec($db); $facturerec->fetch($line->rowid); if ($facturerec->id > 0) @@ -1267,7 +1250,7 @@ dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref.", entity=".$facturerec->entity); - $facture = new Facture($this->db); + $facture = new Facture($db); $facture->fac_rec = $facturerec->id; // We will create $facture from this recurring invoice $facture->fk_fac_rec_source = $facturerec->id; // We will create $facture from this recurring invoice @@ -1305,7 +1288,9 @@ $error++; } } - } else { + } + else + { $error++; $this->error = "Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity."\n"; $this->errors[] = "Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity; @@ -1314,12 +1299,14 @@ if (!$error && $invoiceidgenerated >= 0) { - $this->db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); + $db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); dol_syslog("createRecurringInvoices Process invoice template ".$facturerec->ref." is finished with a success generation"); $nb_create++; $this->output .= $langs->trans("InvoiceGeneratedFromTemplate", $facture->ref, $facturerec->ref)."\n"; - } else { - $this->db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); + } + else + { + $db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); } $parameters = array( @@ -1336,7 +1323,8 @@ } $conf->entity = $saventity; // Restore entity context - } else dol_print_error($this->db); + } + else dol_print_error($db); $this->output = trim($this->output); @@ -1351,8 +1339,8 @@ * @param int $max Maxlength of 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 + * @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 = '', $save_lastsearch_value = -1) @@ -1379,17 +1367,17 @@ } } - $url = DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$this->id; - - if ($short) return $url; - - 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'; - } + $url = DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$this->id; + + if ($short) return $url; + + 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'; + } $linkstart = ''; $linkend = ''; @@ -1414,7 +1402,7 @@ return $this->LibStatut($this->frequency ? 1 : 0, $this->suspended, $mode, $alreadypaid, empty($this->type) ? 0 : $this->type); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return label of a status * @@ -1427,7 +1415,7 @@ */ public function LibStatut($recur, $status, $mode = 0, $alreadypaid = -1, $type = 0) { - // phpcs:enable + // phpcs:enable global $langs; $langs->load('bills'); @@ -1442,54 +1430,69 @@ { if ($status == self::STATUS_SUSPENDED) { $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $labelStatus = $langs->trans('Active'); } - } else { + } + else + { if ($status == self::STATUS_SUSPENDED) { $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $labelStatus = $langs->trans("Draft"); } } - } elseif ($mode == 1) + } + elseif ($mode == 1) { $prefix = 'Short'; if ($recur) { if ($status == self::STATUS_SUSPENDED) { $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $labelStatus = $langs->trans('Active'); } - } else { + } + else + { if ($status == self::STATUS_SUSPENDED) { $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $labelStatus = $langs->trans("Draft"); } } - } elseif ($mode == 2) + } + elseif ($mode == 2) { if ($recur) { if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $statusType = 'status4'; $labelStatus = $langs->trans('Active'); } - } else { + } + else + { if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $statusType = 'status0'; $labelStatus = $langs->trans('Draft'); } } - } elseif ($mode == 3) + } + elseif ($mode == 3) { if ($recur) { @@ -1497,20 +1500,25 @@ if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $statusType = 'status4'; $labelStatus = $langs->trans('Active'); } - } else { + } + else + { if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $statusType = 'status0'; $labelStatus = $langs->trans('Draft'); } } - } elseif ($mode == 4) + } + elseif ($mode == 4) { $prefix = ''; if ($recur) @@ -1518,20 +1526,25 @@ if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $statusType = 'status4'; $labelStatus = $langs->trans('Active'); } - } else { + } + else + { if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $statusType = 'status0'; $labelStatus = $langs->trans('Draft'); } } - } elseif ($mode == 5 || $mode == 6) + } + elseif ($mode == 5 || $mode == 6) { $prefix = ''; if ($mode == 5) $prefix = 'Short'; @@ -1540,15 +1553,19 @@ if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $statusType = 'status4'; $labelStatus = $langs->trans('Active'); } - } else { + } + else + { if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); - } else { + } + else { $statusType = 'status0'; $labelStatus = $langs->trans('Draft'); } @@ -1576,15 +1593,13 @@ $arraynow = dol_getdate($now); $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']); - // Load array of products prodids + // Load array of products prodids $num_prods = 0; $prodids = array(); $sql = "SELECT rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."product"; $sql .= " WHERE entity IN (".getEntity('product').")"; - $sql .= $this->db->plimit(100); - $resql = $this->db->query($sql); if ($resql) { @@ -1639,14 +1654,16 @@ $line->total_ht = -100; $line->total_ttc = -119.6; $line->total_tva = -19.6; - } elseif ($xnbp == 2) // UP is negative (free line) + } + elseif ($xnbp == 2) // UP is negative (free line) { $line->subprice = -100; $line->total_ht = -100; $line->total_ttc = -119.6; $line->total_tva = -19.6; $line->remise_percent = 0; - } elseif ($xnbp == 3) // Discount is 50% (product line) + } + elseif ($xnbp == 3) // Discount is 50% (product line) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; @@ -1654,7 +1671,8 @@ $line->total_ttc = 59.8; $line->total_tva = 9.8; $line->remise_percent = 50; - } else // (product line) + } + else // (product line) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; @@ -1713,190 +1731,202 @@ } /** - * Update frequency and unit - * - * @param int $frequency value of frequency - * @param string $unit unit of frequency (d, m, y) - * @return int <0 if KO, >0 if OK - */ - public function setFrequencyAndUnit($frequency, $unit) - { - if (!$this->table_element) { - dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - - if (!empty($frequency) && empty($unit)) { - dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with params frequency defined but unit not defined", LOG_ERR); - return -2; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET frequency = '.($frequency ? $this->db->escape($frequency) : 'null'); - if (!empty($unit)) { - $sql .= ', unit_frequency = \''.$this->db->escape($unit).'\''; - } - $sql .= ' WHERE rowid = '.$this->id; - - dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG); - if ($this->db->query($sql)) { - $this->frequency = $frequency; - if (!empty($unit)) $this->unit_frequency = $unit; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Update the next date of execution - * - * @param datetime $date date of execution - * @param int $increment_nb_gen_done 0 do nothing more, >0 increment nb_gen_done - * @return int <0 if KO, >0 if OK - */ - public function setNextDate($date, $increment_nb_gen_done = 0) - { - if (!$this->table_element) - { - dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null"); - if ($increment_nb_gen_done > 0) $sql .= ', nb_gen_done = nb_gen_done + 1'; - $sql .= ' WHERE rowid = '.$this->id; - - dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->date_when = $date; - if ($increment_nb_gen_done > 0) $this->nb_gen_done++; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Update the maximum period - * - * @param int $nb number of maximum period - * @return int <0 if KO, >0 if OK - */ - public function setMaxPeriod($nb) - { - if (!$this->table_element) - { - dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - - if (empty($nb)) $nb = 0; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET nb_gen_max = '.$nb; - $sql .= ' WHERE rowid = '.$this->id; - - dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->nb_gen_max = $nb; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Update the auto validate flag of invoice - * - * @param int $validate 0 to create in draft, 1 to create and validate invoice - * @return int <0 if KO, >0 if OK - */ - public function setAutoValidate($validate) - { - if (!$this->table_element) - { - dol_syslog(get_class($this)."::setAutoValidate was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET auto_validate = '.$validate; - $sql .= ' WHERE rowid = '.$this->id; - - dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->auto_validate = $validate; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Update the auto generate documents - * - * @param int $validate 0 no document, 1 to generate document - * @return int <0 if KO, >0 if OK - */ - public function setGeneratePdf($validate) - { - if (!$this->table_element) - { - dol_syslog(get_class($this)."::setGeneratePdf was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET generate_pdf = '.$validate; - $sql .= ' WHERE rowid = '.$this->id; - - dol_syslog(get_class($this)."::setGeneratePdf", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->generate_pdf = $validate; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Update the model for documents - * - * @param string $model model of document generator - * @return int <0 if KO, >0 if OK - */ - public function setModelPdf($model) - { - if (!$this->table_element) - { - dol_syslog(get_class($this)."::setModelPdf was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET modelpdf = "'.$model.'"'; - $sql .= ' WHERE rowid = '.$this->id; - - dol_syslog(get_class($this)."::setModelPdf", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->modelpdf = $model; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } + * Update frequency and unit + * + * @param int $frequency value of frequency + * @param string $unit unit of frequency (d, m, y) + * @return int <0 if KO, >0 if OK + */ + public function setFrequencyAndUnit($frequency, $unit) + { + if (!$this->table_element) { + dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + + if (!empty($frequency) && empty($unit)) { + dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with params frequency defined but unit not defined", LOG_ERR); + return -2; + } + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET frequency = '.($frequency ? $this->db->escape($frequency) : 'null'); + if (!empty($unit)) { + $sql .= ', unit_frequency = \''.$this->db->escape($unit).'\''; + } + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG); + if ($this->db->query($sql)) { + $this->frequency = $frequency; + if (!empty($unit)) $this->unit_frequency = $unit; + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Update the next date of execution + * + * @param datetime $date date of execution + * @param int $increment_nb_gen_done 0 do nothing more, >0 increment nb_gen_done + * @return int <0 if KO, >0 if OK + */ + public function setNextDate($date, $increment_nb_gen_done = 0) + { + if (!$this->table_element) + { + dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null"); + if ($increment_nb_gen_done > 0) $sql .= ', nb_gen_done = nb_gen_done + 1'; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->date_when = $date; + if ($increment_nb_gen_done > 0) $this->nb_gen_done++; + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Update the maximum period + * + * @param int $nb number of maximum period + * @return int <0 if KO, >0 if OK + */ + public function setMaxPeriod($nb) + { + if (!$this->table_element) + { + dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + + if (empty($nb)) $nb = 0; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET nb_gen_max = '.$nb; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->nb_gen_max = $nb; + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Update the auto validate flag of invoice + * + * @param int $validate 0 to create in draft, 1 to create and validate invoice + * @return int <0 if KO, >0 if OK + */ + public function setAutoValidate($validate) + { + if (!$this->table_element) + { + dol_syslog(get_class($this)."::setAutoValidate was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET auto_validate = '.$validate; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->auto_validate = $validate; + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Update the auto generate documents + * + * @param int $validate 0 no document, 1 to generate document + * @return int <0 if KO, >0 if OK + */ + public function setGeneratePdf($validate) + { + if (!$this->table_element) + { + dol_syslog(get_class($this)."::setGeneratePdf was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET generate_pdf = '.$validate; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setGeneratePdf", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->generate_pdf = $validate; + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Update the model for documents + * + * @param string $model model of document generator + * @return int <0 if KO, >0 if OK + */ + public function setModelPdf($model) + { + if (!$this->table_element) + { + dol_syslog(get_class($this)."::setModelPdf was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET modelpdf = "'.$model.'"'; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setModelPdf", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->modelpdf = $model; + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } } @@ -1917,229 +1947,214 @@ */ public $table_element = 'facturedet_rec'; - - - /** - * Delete line in database - * - * @param User $user Object user - * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function delete(User $user, $notrigger = false) - { - $error = 0; - - $this->db->begin(); - - if (!$error) { - if (!$notrigger) { - // Call triggers - $result = $this->call_trigger('LINEBILLREC_DELETE', $user); - if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail - // End call triggers - } - } + public $date_start_fill; + public $date_end_fill; + + + /** + * Delete line in database + * + * @param User $user Object user + * @param int $notrigger Disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + $error = 0; + + $this->db->begin(); + + if (!$error) { + if (!$notrigger) { + // Call triggers + $result = $this->call_trigger('LINEBILLREC_DELETE', $user); + if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail + // End call triggers + } + } if (!$error) - { - $result = $this->deleteExtraFields(); - if ($result < 0) { - $error++; - } - } - - if (!$error) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; - - $res = $this->db->query($sql); - if ($res === false) { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } - - // Commit or rollback + { + $result = $this->deleteExtraFields(); + if ($result < 0) { + $error++; + } + } + + if (!$error) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; + + $res = $this->db->query($sql); + if ($res === false) { + $error++; + $this->errors[] = $this->db->lasterror(); + } + } + + // Commit or rollback if ($error) { - $this->db->rollback(); - return -1; + $this->db->rollback(); + return -1; } else { - $this->db->commit(); - return 1; - } - } - - - /** - * Get line of template invoice - * - * @param int $rowid Id of invoice - * @return int 1 if OK, < 0 if KO - */ - public function fetch($rowid) - { - $sql = 'SELECT l.rowid, l.fk_facture ,l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; - $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; - $sql .= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; - $sql .= ' l.rang, l.special_code,'; - $sql .= ' l.fk_unit, l.fk_contract_line,'; - $sql .= ' l.import_key, l.fk_multicurrency,'; - $sql .= ' l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,'; - $sql .= ' l.buy_price_ht, l.fk_product_fournisseur_price,'; - $sql .= ' l.fk_user_author, l.fk_user_modif,'; - $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; - $sql .= ' WHERE l.rowid = '.$rowid; - $sql .= ' ORDER BY l.rang'; - - dol_syslog('FactureRec::fetch', LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $objp = $this->db->fetch_object($result); - - $this->id = $objp->rowid; - $this->label = $objp->custom_label; // Label line - $this->desc = $objp->description; // Description line - $this->description = $objp->description; // Description line - $this->product_type = $objp->product_type; // Type of line - $this->ref = $objp->product_ref; // Ref product - $this->product_ref = $objp->product_ref; // Ref product - $this->libelle = $objp->product_label; // deprecated - $this->product_label = $objp->product_label; // Label product - $this->product_desc = $objp->product_desc; // Description product - $this->fk_product_type = $objp->fk_product_type; // Type of product - $this->qty = $objp->qty; - $this->price = $objp->price; - $this->subprice = $objp->subprice; - $this->fk_facture = $objp->fk_facture; - $this->vat_src_code = $objp->vat_src_code; - $this->tva_tx = $objp->tva_tx; - $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->remise_percent = $objp->remise_percent; - //$this->fk_remise_except = $objp->fk_remise_except; - $this->fk_product = $objp->fk_product; - $this->date_start_fill = $objp->date_start_fill; - $this->date_end_fill = $objp->date_end_fill; - $this->info_bits = $objp->info_bits; - $this->total_ht = $objp->total_ht; - $this->total_tva = $objp->total_tva; - $this->total_ttc = $objp->total_ttc; - //$this->code_ventilation = $objp->fk_code_ventilation; - $this->rang = $objp->rang; - $this->special_code = $objp->special_code; - $this->fk_unit = $objp->fk_unit; - $this->fk_contract_line = $objp->fk_contract_line; - $this->import_key = $objp->import_key; - $this->fk_multicurrency = $objp->fk_multicurrency; - $this->multicurrency_code = $objp->multicurrency_code; - $this->multicurrency_subprice = $objp->multicurrency_subprice; - $this->multicurrency_total_ht = $objp->multicurrency_total_ht; - $this->multicurrency_total_tva = $objp->multicurrency_total_tva; - $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc; - $this->buy_price_ht = $objp->buy_price_ht; - $this->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price; - $this->fk_user_author = $objp->fk_user_author; - $this->fk_user_modif = $objp->fk_user_modif; - - $this->db->free($result); - return 1; - } else { - $this->error = $this->db->lasterror(); - return -3; - } - } - - - /** - * Update a line to invoice_rec. - * - * @param User $user User - * @param int $notrigger No trigger - * @return int <0 if KO, Id of line if OK - */ - public function update(User $user, $notrigger = 0) - { - global $conf; - - $error = 0; - - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - - $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET"; - $sql .= " fk_facture = ".$this->fk_facture; - $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); - $sql .= ", description='".$this->db->escape($this->desc)."'"; - $sql .= ", price=".price2num($this->price); - $sql .= ", qty=".price2num($this->qty); - $sql .= ", tva_tx=".price2num($this->tva_tx); - $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'"; - $sql .= ", localtax1_tx=".price2num($this->localtax1_tx); - $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; - $sql .= ", localtax2_tx=".price2num($this->localtax2_tx); - $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql .= ", fk_product=".($this->fk_product > 0 ? $this->fk_product : "null"); - $sql .= ", product_type=".$this->product_type; - $sql .= ", remise_percent='".price2num($this->remise_percent)."'"; - $sql .= ", subprice='".price2num($this->subprice)."'"; - $sql .= ", info_bits='".price2num($this->info_bits)."'"; - $sql .= ", date_start_fill=".(int) $this->date_start_fill; - $sql .= ", date_end_fill=".(int) $this->date_end_fill; - if (empty($this->skip_update_total)) { - $sql .= ", total_ht=".price2num($this->total_ht); - $sql .= ", total_tva=".price2num($this->total_tva); - $sql .= ", total_localtax1=".price2num($this->total_localtax1); - $sql .= ", total_localtax2=".price2num($this->total_localtax2); - $sql .= ", total_ttc=".price2num($this->total_ttc); - } - $sql .= ", rang=".$this->rang; - $sql .= ", special_code=".$this->special_code; - $sql .= ", fk_unit=".($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null"); - $sql .= ", fk_contract_line=".($this->fk_contract_line ? $this->fk_contract_line : "null"); - $sql .= " WHERE rowid = ".$this->id; - - $this->db->begin(); - - dol_syslog(get_class($this)."::updateline", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('LINEBILLREC_UPDATE', $user); - if ($result < 0) - { - $error++; - } - // End call triggers - } - - if ($error) { - $this->db->rollback(); - return -2; - } else { - $this->db->commit(); - return 1; - } - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -2; - } - } + $this->db->commit(); + return 1; + } + } + + + /** + * Get line of template invoice + * + * @param int $rowid Id of invoice + * @return int 1 if OK, < 0 if KO + */ + public function fetch($rowid) + { + $sql = 'SELECT l.rowid, l.fk_facture ,l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; + $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; + $sql .= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; + $sql .= ' l.rang, l.special_code,'; + $sql .= ' l.fk_unit, l.fk_contract_line,'; + $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; + $sql .= ' WHERE l.rowid = '.$rowid; + $sql .= ' ORDER BY l.rang'; + + dol_syslog('FactureRec::fetch', LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $objp = $this->db->fetch_object($result); + + $this->id = $objp->rowid; + $this->label = $objp->custom_label; // Label line + $this->desc = $objp->description; // Description line + $this->description = $objp->description; // Description line + $this->product_type = $objp->product_type; // Type of line + $this->ref = $objp->product_ref; // Ref product + $this->product_ref = $objp->product_ref; // Ref product + $this->libelle = $objp->product_label; // deprecated + $this->product_label = $objp->product_label; // Label product + $this->product_desc = $objp->product_desc; // Description product + $this->fk_product_type = $objp->fk_product_type; // Type of product + $this->qty = $objp->qty; + $this->price = $objp->price; + $this->subprice = $objp->subprice; + $this->fk_facture = $objp->fk_facture; + $this->vat_src_code = $objp->vat_src_code; + $this->tva_tx = $objp->tva_tx; + $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->remise_percent = $objp->remise_percent; + $this->fk_remise_except = $objp->fk_remise_except; + $this->fk_product = $objp->fk_product; + $this->date_start_fill = $objp->date_start_fill; + $this->date_end_fill = $objp->date_end_fill; + $this->info_bits = $objp->info_bits; + $this->total_ht = $objp->total_ht; + $this->total_tva = $objp->total_tva; + $this->total_ttc = $objp->total_ttc; + $this->code_ventilation = $objp->fk_code_ventilation; + $this->rang = $objp->rang; + $this->special_code = $objp->special_code; + $this->fk_unit = $objp->fk_unit; + $this->fk_contract_line = $objp->fk_contract_line; + + + $this->db->free($result); + return 1; + } + else + { + $this->error = $this->db->lasterror(); + return -3; + } + } + + + /** + * Update a line to invoice_rec. + * + * @param User $user User + * @param int $notrigger No trigger + * @return int <0 if KO, Id of line if OK + */ + public function update(User $user, $notrigger = 0) + { + global $conf; + + $error = 0; + + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET"; + $sql .= " fk_facture = ".$this->fk_facture; + $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= ", description='".$this->db->escape($this->desc)."'"; + $sql .= ", price=".price2num($this->price); + $sql .= ", qty=".price2num($this->qty); + $sql .= ", tva_tx=".price2num($this->tva_tx); + $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'"; + $sql .= ", localtax1_tx=".price2num($this->localtax1_tx); + $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; + $sql .= ", localtax2_tx=".price2num($this->localtax2_tx); + $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; + $sql .= ", fk_product=".($this->fk_product > 0 ? $this->fk_product : "null"); + $sql .= ", product_type=".$this->product_type; + $sql .= ", remise_percent='".price2num($this->remise_percent)."'"; + $sql .= ", subprice='".price2num($this->subprice)."'"; + $sql .= ", info_bits='".price2num($this->info_bits)."'"; + $sql .= ", date_start_fill=".(int) $this->date_start_fill; + $sql .= ", date_end_fill=".(int) $this->date_end_fill; + if (empty($this->skip_update_total)) { + $sql .= ", total_ht=".price2num($this->total_ht); + $sql .= ", total_tva=".price2num($this->total_tva); + $sql .= ", total_localtax1=".price2num($this->total_localtax1); + $sql .= ", total_localtax2=".price2num($this->total_localtax2); + $sql .= ", total_ttc=".price2num($this->total_ttc); + } + $sql .= ", rang=".$this->rang; + $sql .= ", special_code=".$this->special_code; + $sql .= ", fk_unit=".($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null"); + $sql .= ", fk_contract_line=".($this->fk_contract_line ? $this->fk_contract_line : "null"); + $sql .= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::updateline", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('LINEBILLREC_UPDATE', $user); + if ($result < 0) + { + $this->db->rollback(); + return -2; + } + // End call triggers + } + $this->db->commit(); + return 1; + } + else + { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -2; + } + } } --- /tmp/dsg/dolibarr/htdocs/compta/facture/class/github_facture.class.php +++ /tmp/dsg/dolibarr/htdocs/compta/facture/class/client_facture.class.php @@ -7,7 +7,7 @@ * Copyright (C) 2005-2014 Regis Houssin * Copyright (C) 2006 Andre Cianfarani * Copyright (C) 2007 Franky Van Liedekerke - * Copyright (C) 2010-2020 Juanjo Menent + * Copyright (C) 2010-2016 Juanjo Menent * Copyright (C) 2012-2014 Christophe Battarel * Copyright (C) 2012-2015 Marcos García * Copyright (C) 2012 Cédric Salvador @@ -64,17 +64,17 @@ public $table_element = 'facture'; /** - * @var string Name of subtable line + * @var int Name of subtable line */ public $table_element_line = 'facturedet'; /** - * @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 */ public $fk_element = 'fk_facture'; /** - * @var string String with name of icon for myobject. + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ public $picto = 'bill'; @@ -95,37 +95,22 @@ */ protected $table_ref_field = 'ref'; - /** - * @var int thirdparty ID - */ public $socid; public $author; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_author; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_valid; public $date; // Date invoice public $datem; - - /** - * @var int Date expected for delivery - * @deprecated - */ - public $date_livraison; // deprecated; Use delivery_date instead. - - public $delivery_date; // Date expected of shipment (date starting shipment, not the reception that occurs some days after) - - /** - * @var string customer ref - */ public $ref_client; /** @@ -152,12 +137,8 @@ public $close_code; //! Commentaire si mis a paye sans paiement complet public $close_note; - - /** - * 1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code) - */ + //! 1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code) public $paye; - //! key of module source when invoice generated from a dedicated module ('cashdesk', 'takepos', ...) public $module_source; //! key of pos source ('0', '1', ...) @@ -172,9 +153,14 @@ public $mode_reglement_code; // Code in llx_c_paiement /** - * @var int ID Field to store bank id to use when payment mode is withdraw - */ + * @var int ID Field to store bank id to use when payment mode is withdraw + */ public $fk_bank; + + /** + * @deprecated + */ + public $products = array(); /** * @var FactureLigne[] @@ -183,15 +169,14 @@ public $line; public $extraparams = array(); + public $specimen; public $fac_rec; - public $date_pointoftax; - // Multicurrency /** - * @var int ID - */ + * @var int ID + */ public $fk_multicurrency; public $multicurrency_code; @@ -338,30 +323,30 @@ ); // END MODULEBUILDER PROPERTIES - /** - * Standard invoice - */ - const TYPE_STANDARD = 0; - - /** - * Replacement invoice - */ - const TYPE_REPLACEMENT = 1; - - /** - * Credit note invoice - */ - const TYPE_CREDIT_NOTE = 2; - - /** - * Deposit invoice - */ - const TYPE_DEPOSIT = 3; - - /** - * Proforma invoice (should not be used. a proforma is an order) - */ - const TYPE_PROFORMA = 4; + /** + * Standard invoice + */ + const TYPE_STANDARD = 0; + + /** + * Replacement invoice + */ + const TYPE_REPLACEMENT = 1; + + /** + * Credit note invoice + */ + const TYPE_CREDIT_NOTE = 2; + + /** + * Deposit invoice + */ + const TYPE_DEPOSIT = 3; + + /** + * Proforma invoice (should not be used. a proforma is an order) + */ + const TYPE_PROFORMA = 4; /** * Situation invoice @@ -422,7 +407,7 @@ * @param int $forceduedate If set, do not recalculate due date from payment condition but force it with value * @return int <0 if KO, >0 if OK */ - public function create(User $user, $notrigger = 0, $forceduedate = 0) + public function create(User $user, $notrigger = 0, $forceduedate = 0) { global $langs, $conf, $mysoc, $hookmanager; $error = 0; @@ -438,7 +423,7 @@ $this->brouillon = 1; // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate) - if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code); else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); if (empty($this->fk_multicurrency)) { @@ -473,10 +458,10 @@ $nextdatewhen = null; $previousdaynextdatewhen = null; - // Create invoice from a template recurring invoice + // Create invoice from a template invoice if ($this->fac_rec > 0) { - $this->fk_fac_rec_source = $this->fac_rec; + $this->fk_fac_rec_source = $this->fac_rec; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; $_facrec = new FactureRec($this->db); @@ -496,8 +481,8 @@ // Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI $this->fk_project = GETPOST('projectid', 'int') > 0 ? ((int) GETPOST('projectid', 'int')) : $_facrec->fk_project; - $this->note_public = GETPOST('note_public', 'none') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public; - $this->note_private = GETPOST('note_private', 'none') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private; + $this->note_public = GETPOST('note_public', 'none') ? GETPOST('note_public', 'none') : $_facrec->note_public; + $this->note_private = GETPOST('note_private', 'none') ? GETPOST('note_private', 'none') : $_facrec->note_private; $this->modelpdf = GETPOST('model', 'alpha') ? GETPOST('model', 'alpha') : $_facrec->modelpdf; $this->cond_reglement_id = GETPOST('cond_reglement_id', 'int') > 0 ? ((int) GETPOST('cond_reglement_id', 'int')) : $_facrec->cond_reglement_id; $this->mode_reglement_id = GETPOST('mode_reglement_id', 'int') > 0 ? ((int) GETPOST('mode_reglement_id', 'int')) : $_facrec->mode_reglement_id; @@ -518,9 +503,9 @@ $this->ref_client = trim($this->ref_client); $this->note_public = trim($this->note_public); $this->note_private = trim($this->note_private); - $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref)); - - $this->array_options = $_facrec->array_options; + $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref)); + + $this->array_options = $_facrec->array_options; //if (! $this->remise) $this->remise = 0; if (!$this->mode_reglement_id) $this->mode_reglement_id = 0; @@ -535,12 +520,12 @@ // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice if ($_facrec->frequency > 0) { - dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when"); - if (empty($_facrec->date_when)) $_facrec->date_when = $now; - $next_date = $_facrec->getNextDate(); // Calculate next date - $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, ''); - //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1. - $result = $_facrec->setNextDate($next_date, 1); + dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when"); + if (empty($_facrec->date_when)) $_facrec->date_when = $now; + $next_date = $_facrec->getNextDate(); // Calculate next date + $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, ''); + //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1. + $result = $_facrec->setNextDate($next_date, 1); } // Define lang of customer @@ -551,8 +536,8 @@ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) $newlang = $this->default_lang; // for thirdparty if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); } // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) @@ -582,16 +567,16 @@ } // Define due date if not already defined - if (empty($forceduedate)) { - $duedate = $this->calculate_date_lim_reglement(); - /*if ($duedate < 0) { Regression, a date can be negative if before 1970. + if (empty($forceduedate)) { + $duedate = $this->calculate_date_lim_reglement(); + /*if ($duedate < 0) { Regression, a date can be negative if before 1970. dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR); return -1; }*/ - $this->date_lim_reglement = $duedate; - } else { - $this->date_lim_reglement = $forceduedate; - } + $this->date_lim_reglement = $duedate; + } else { + $this->date_lim_reglement = $forceduedate; + } // Insert into database $socid = $this->socid; @@ -610,29 +595,29 @@ $sql .= ", note_private"; $sql .= ", note_public"; $sql .= ", ref_client, ref_int"; - $sql .= ", fk_account"; + $sql .= ", fk_account"; $sql .= ", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet"; $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf"; $sql .= ", situation_cycle_ref, situation_counter, situation_final"; $sql .= ", fk_incoterms, location_incoterms"; - $sql .= ", fk_multicurrency"; - $sql .= ", multicurrency_code"; - $sql .= ", multicurrency_tx"; - $sql .= ", retained_warranty"; - $sql .= ", retained_warranty_date_limit"; - $sql .= ", retained_warranty_fk_cond_reglement"; + $sql .= ", fk_multicurrency"; + $sql .= ", multicurrency_code"; + $sql .= ", multicurrency_tx"; + $sql .= ", retained_warranty"; + $sql .= ", retained_warranty_date_limit"; + $sql .= ", retained_warranty_fk_cond_reglement"; $sql .= ")"; $sql .= " VALUES ("; $sql .= "'(PROV)'"; $sql .= ", ".setEntity($this); $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null"); $sql .= ", '".$this->db->escape($this->type)."'"; - $sql .= ", ".((int) $socid); + $sql .= ", '".$socid."'"; $sql .= ", '".$this->db->idate($now)."'"; $sql .= ", ".($this->remise_absolue > 0 ? $this->remise_absolue : 'NULL'); $sql .= ", ".($this->remise_percent > 0 ? $this->remise_percent : 'NULL'); $sql .= ", '".$this->db->idate($this->date)."'"; - $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'"); + $sql .= ", ".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null'); $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null"); $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null"); $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null"); @@ -642,17 +627,16 @@ $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null"); $sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape($this->fk_fac_rec_source)."'" : "null"); $sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null"); - $sql .= ", ".($user->id > 0 ? (int) $user->id : "null"); + $sql .= ", ".($user->id > 0 ? "'".$user->id."'" : "null"); $sql .= ", ".($this->fk_project ? $this->fk_project : "null"); $sql .= ", ".$this->cond_reglement_id; $sql .= ", ".$this->mode_reglement_id; - $sql .= ", '".$this->db->idate($this->date_lim_reglement)."'"; - $sql .= ", ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null"); + $sql .= ", '".$this->db->idate($this->date_lim_reglement)."', '".$this->db->escape($this->modelpdf)."'"; $sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape($this->situation_cycle_ref)."'" : "null"); $sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null"); $sql .= ", ".($this->situation_final ? $this->situation_final : 0); $sql .= ", ".(int) $this->fk_incoterms; - $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; $sql .= ", ".(int) $this->fk_multicurrency; $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; $sql .= ", ".(double) $this->multicurrency_tx; @@ -679,31 +663,32 @@ } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) + if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) { foreach ($this->linked_objects as $origin => $tmp_origin_id) { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { - $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { - $this->error = $this->db->lasterror(); - $error++; - } - } - } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) - { - $origin_id = $tmp_origin_id; - $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { - $this->error = $this->db->lasterror(); - $error++; - } - } + if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + { + foreach ($tmp_origin_id as $origin_id) + { + $ret = $this->add_object_linked($origin, $origin_id); + if (!$ret) + { + $this->error = $this->db->lasterror(); + $error++; + } + } + } + else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) + { + $origin_id = $tmp_origin_id; + $ret = $this->add_object_linked($origin, $origin_id); + if (!$ret) + { + $this->error = $this->db->lasterror(); + $error++; + } + } } } @@ -714,34 +699,35 @@ $originidforcontact = $this->origin_id; if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order { - require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; - $exp = new Expedition($this->db); - $exp->fetch($this->origin_id); - $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); - if (count($exp->linkedObjectsIds['commande']) > 0) - { - foreach ($exp->linkedObjectsIds['commande'] as $key => $value) - { - $originforcontact = 'commande'; - if (is_object($value)) $originidforcontact = $value->id; - else $originidforcontact = $value; - break; // We take first one - } - } + require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; + $exp = new Expedition($this->db); + $exp->fetch($this->origin_id); + $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); + if (count($exp->linkedObjectsIds['commande']) > 0) + { + foreach ($exp->linkedObjectsIds['commande'] as $key => $value) + { + $originforcontact = 'commande'; + if (is_object($value)) $originidforcontact = $value->id; + else $originidforcontact = $value; + break; // We take first one + } + } } $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; - $sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'"; + $sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'"; $resqlcontact = $this->db->query($sqlcontact); if ($resqlcontact) { - while ($objcontact = $this->db->fetch_object($resqlcontact)) - { - //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n"; - $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object - } - } else dol_print_error($resqlcontact); + while ($objcontact = $this->db->fetch_object($resqlcontact)) + { + //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n"; + $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object + } + } + else dol_print_error($resqlcontact); } /* @@ -761,7 +747,7 @@ $newinvoiceline->origin_id = $this->lines[$i]->id; // Auto set date of service ? - if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) // $originaldatewhen is defined when generating from recurring invoice only + if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) // $originaldatewhen is defined when generating from recurring invoice only { $newinvoiceline->date_start = $originaldatewhen; } @@ -780,12 +766,12 @@ $newinvoiceline->fk_parent_line = $fk_parent_line; if ($this->type === Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) { - $discount = new DiscountAbsolute($this->db); - $discount->fetch($newinvoiceline->fk_remise_except); - - $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx); - $newinvoiceline->fk_remise_except = $discountId; - } + $discount = new DiscountAbsolute($this->db); + $discount->fetch($newinvoiceline->fk_remise_except); + + $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx); + $newinvoiceline->fk_remise_except = $discountId; + } $result = $newinvoiceline->insert(); @@ -797,12 +783,12 @@ if ($result < 0) { $this->error = $newinvoiceline->error; - $this->errors = $newinvoiceline->errors; $error++; break; } } - } elseif (!$error && empty($this->fac_rec)) // If this->lines is an array of invoice line arrays + } + elseif (!$error && empty($this->fac_rec)) // If this->lines is an array of invoice line arrays { $fk_parent_line = 0; @@ -810,13 +796,13 @@ foreach ($this->lines as $i => $val) { - $line = $this->lines[$i]; - - // 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; - - if ($result >= 0) + $line = $this->lines[$i]; + + // 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; + + if ($result >= 0) { // Reset fk_parent_line for no child products and special product if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { @@ -835,12 +821,7 @@ $origintype = $this->element; } - // init ref_ext - if (empty($line->ref_ext)) { - $line->ref_ext = ''; - } - - $result = $this->addline( + $result = $this->addline( $line->desc, $line->subprice, $line->qty, @@ -859,8 +840,8 @@ $line->product_type, $line->rang, $line->special_code, - $origintype, - $originid, + $origintype, + $originid, $fk_parent_line, $line->fk_fournprice, $line->pa_ht, @@ -869,8 +850,7 @@ $line->situation_percent, $line->fk_prev_id, $line->fk_unit, - $line->multicurrency_subprice, - $line->ref_ext + $line->pu_ht_devise ); if ($result < 0) { @@ -915,31 +895,30 @@ $localtax1_tx = $_facrec->lines[$i]->localtax1_tx; $localtax2_tx = $_facrec->lines[$i]->localtax2_tx; - $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price; + $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ?null:$_facrec->lines[$i]->fk_product_fournisseur_price; $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice; - // If buyprice not defined from template invoice, we try to guess the best value if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) - { - require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; - $producttmp = new ProductFournisseur($this->db); - $producttmp->fetch($_facrec->lines[$i]->fk_product); - - // If margin module defined on costprice, we try the costprice - // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price - // else we get the best supplier price - if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) $buyprice = $producttmp->cost_price; - elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) $buyprice = $producttmp->pmp; - else { - if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) - { - if ($producttmp->product_fourn_price_id > 0) - { - $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU'); - } - } - } - } + { + require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; + $producttmp = new ProductFournisseur($this->db); + $producttmp->fetch($_facrec->lines[$i]->fk_product); + + // If margin module defined on costprice, we try the costprice + // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price + // else we get the best supplier price + if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) $buyprice = $producttmp->cost_price; + elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) $buyprice = $producttmp->pmp; + else { + if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) + { + if ($producttmp->product_fourn_price_id > 0) + { + $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU'); + } + } + } + } $result_insert = $this->addline( $_facrec->lines[$i]->desc, @@ -963,14 +942,14 @@ '', 0, 0, - $fk_product_fournisseur_price, + $fk_product_fournisseur_price, $buyprice, $_facrec->lines[$i]->label, empty($_facrec->lines[$i]->array_options) ?null:$_facrec->lines[$i]->array_options, $_facrec->lines[$i]->situation_percent, '', $_facrec->lines[$i]->fk_unit, - $_facrec->lines[$i]->multicurrency_subprice + $_facrec->lines[$i]->pu_ht_devise ); if ($result_insert < 0) @@ -985,7 +964,6 @@ if (!$error) { $result = $this->update_price(1); - if ($result > 0) { $action = 'create'; @@ -993,37 +971,45 @@ // Actions on extra fields if (!$error) { - $result = $this->insertExtraFields(); - if ($result < 0) $error++; + $result = $this->insertExtraFields(); + if ($result < 0) $error++; } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('BILL_CREATE', $user); - if ($result < 0) $error++; - // End call triggers - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('BILL_CREATE', $user); + if ($result < 0) $error++; + // End call triggers + } if (!$error) { $this->db->commit(); return $this->id; - } else { + } + else + { $this->db->rollback(); return -4; } - } else { + } + else + { $this->error = $langs->trans('FailedToUpdatePrice'); $this->db->rollback(); return -3; } - } else { + } + else + { dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } - } else { + } + else + { $this->error = $this->db->error(); $this->db->rollback(); return -1; @@ -1038,24 +1024,24 @@ * @param int $invertdetail Reverse sign of amounts for lines * @return int <0 if KO, >0 if OK */ - public function createFromCurrent(User $user, $invertdetail = 0) + public function createFromCurrent(User $user, $invertdetail = 0) { global $conf; // Charge facture source $facture = new Facture($this->db); - // Retrieve all extrafield + // Retreive all extrafield // fetch optionals attributes and labels $this->fetch_optionals(); - if (!empty($this->array_options)) { - $facture->array_options = $this->array_options; - } - - foreach ($this->lines as &$line) { - $line->fetch_optionals(); //fetch extrafields - } + if (!empty($this->array_options)) { + $facture->array_options = $this->array_options; + } + + foreach ($this->lines as &$line) { + $line->fetch_optionals(); //fetch extrafields + } $facture->fk_facture_source = $this->fk_facture_source; $facture->type = $this->type; @@ -1065,8 +1051,7 @@ $facture->note_public = $this->note_public; $facture->note_private = $this->note_private; $facture->ref_client = $this->ref_client; - $facture->modelpdf = $this->modelpdf; // deprecated - $facture->model_pdf = $this->modelpdf; + $facture->modelpdf = $this->modelpdf; $facture->fk_project = $this->fk_project; $facture->cond_reglement_id = $this->cond_reglement_id; $facture->mode_reglement_id = $this->mode_reglement_id; @@ -1077,15 +1062,14 @@ $facture->origin_id = $this->origin_id; $facture->lines = $this->lines; // Array of lines of invoice + $facture->products = $this->lines; // Tant que products encore utilise $facture->situation_counter = $this->situation_counter; $facture->situation_cycle_ref = $this->situation_cycle_ref; $facture->situation_final = $this->situation_final; - $facture->retained_warranty = $this->retained_warranty; - $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement; - $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit; - - $facture->fk_user_author = $user->id; + $facture->retained_warranty = $this->retained_warranty; + $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement; + $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit; // Loop on each line of new invoice @@ -1100,7 +1084,6 @@ $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1; $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2; $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc; - $facture->lines[$i]->ref_ext = ''; } } @@ -1111,7 +1094,8 @@ { $this->error = $facture->error; $this->errors = $facture->errors; - } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) + } + elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) { $this->fetchObjectLinked('', '', $this->id, 'facture'); @@ -1133,7 +1117,7 @@ /** * Load an object from its id and create a new one in database * - * @param User $user User that clone + * @param User $user User that clone * @param int $fromid Id of object to clone * @return int New id of clone */ @@ -1156,11 +1140,11 @@ if ($objsoc->fetch($this->socid) > 0) { - $object->socid = $objsoc->id; - $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); - $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); - $object->fk_project = ''; - $object->fk_delivery_address = ''; + $object->socid = $objsoc->id; + $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); + $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); + $object->fk_project = ''; + $object->fk_delivery_address = ''; } // TODO Change product price if multi-prices @@ -1168,14 +1152,11 @@ $object->id = 0; $object->statut = self::STATUS_DRAFT; - $object->status = self::STATUS_DRAFT; // Clear fields $object->date = (empty($this->date) ? dol_now() : $this->date); - $object->user_author = $user->id; // deprecated - $object->user_valid = null; // deprecated - $object->fk_user_author = $user->id; - $object->fk_user_valid = null; + $object->user_author = $user->id; + $object->user_valid = ''; $object->fk_facture_source = 0; $object->date_creation = ''; $object->date_modification = ''; @@ -1183,6 +1164,7 @@ $object->ref_client = ''; $object->close_code = ''; $object->close_note = ''; + $object->products = $object->lines; // For backward compatibility if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) { $object->note_private = ''; $object->note_public = ''; @@ -1191,28 +1173,28 @@ // Loop on each line of new invoice foreach ($object->lines as $i => $line) { - if (($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts - { - unset($object->lines[$i]); - continue; - } - - // Bloc to update dates of service (month by month only if previously filled and similare to start and end of month) + if (($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts + { + unset($object->lines[$i]); + unset($object->products[$i]); // Tant que products encore utilise + } + // Bloc to update dates of service (month by month only if previously filled at 1d near start or end of month) // If it's a service with start and end dates - if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) { + if (!empty($line->date_start) && !empty($line->date_end) ) { // Get the dates $start = dol_getdate($line->date_start); $end = dol_getdate($line->date_end); // Get the first and last day of the month $first = dol_get_first_day($start['year'], $start['mon']); - $last = dol_get_last_day($end['year'], $end['mon']); - - //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'
'; - //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'
';exit; - // If start date is first date of month and end date is last date of month - if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first - && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) { + $last = dol_get_first_day($end['year'], $end['mon']); + + // Get diff betweend start/end of month and previously filled + $diffFirst = num_between_day($first, dol_mktime($start['hours'], $start['minutes'], $start['seconds'], $start['mon'], $start['mday'], $start['year'], 'user')); + $diffLast = num_between_day(dol_mktime($end['hours'], $end['minutes'], $end['seconds'], $end['mon'], $end['mday'], $end['year'], 'user'), $last); + + // If there is <= 1d (or 2?) of start/or/end of month + if ($diffFirst <= 2 && $diffLast <= 2) { $nextMonth = dol_get_next_month($end['mon'], $end['year']); $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']); $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']); @@ -1220,8 +1202,6 @@ $object->lines[$i]->date_end = $newLast; } } - - $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext } // Create clone @@ -1230,13 +1210,13 @@ if ($result < 0) $error++; else { // copy internal contacts - if ($object->copy_linked_contact($this, 'internal') < 0) + if ($object->copy_linked_contact($this, 'internal') < 0) $error++; // copy external contacts if same company elseif ($this->socid == $object->socid) { - if ($object->copy_linked_contact($this, 'external') < 0) + if ($object->copy_linked_contact($this, 'external') < 0) $error++; } } @@ -1260,7 +1240,9 @@ { $this->db->commit(); return $object->id; - } else { + } + else + { $this->db->rollback(); return -1; } @@ -1273,7 +1255,7 @@ * @param User $user Object user * @return int <0 if KO, 0 if nothing done, 1 if OK */ - public function createFromOrder($object, User $user) + public function createFromOrder($object, User $user) { global $conf, $hookmanager; @@ -1326,11 +1308,10 @@ $marginInfos = getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht); $line->pa_ht = $marginInfos[0]; - // get extrafields from original line + // get extrafields from original line $object->lines[$i]->fetch_optionals(); - foreach ($object->lines[$i]->array_options as $options_key => $value) { + foreach ($object->lines[$i]->array_options as $options_key => $value) $line->array_options[$options_key] = $value; - } $this->lines[$i] = $line; } @@ -1342,27 +1323,24 @@ $this->mode_reglement_id = $object->mode_reglement_id; $this->availability_id = $object->availability_id; $this->demand_reason_id = $object->demand_reason_id; - $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date); - $this->date_livraison = $object->delivery_date; // deprecated + $this->date_livraison = $object->date_livraison; $this->fk_delivery_address = $object->fk_delivery_address; // deprecated - $this->contact_id = $object->contact_id; + $this->contact_id = $object->contactid; $this->ref_client = $object->ref_client; if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) { - $this->note_private = $object->note_private; - $this->note_public = $object->note_public; - } - - $this->module_source = $object->module_source; + $this->note_private = $object->note_private; + $this->note_public = $object->note_public; + } + + $this->module_source = $object->module_source; $this->pos_source = $object->pos_source; $this->origin = $object->element; $this->origin_id = $object->id; - $this->fk_user_author = $user->id; - - // get extrafields from original line + // get extrafields from original line $object->fetch_optionals(); foreach ($object->array_options as $options_key => $value) $this->array_options[$options_key] = $value; @@ -1376,7 +1354,8 @@ $ret = $this->create($user); - if ($ret > 0) { + if ($ret > 0) + { // Actions hooked (by external module) $hookmanager->initHooks(array('invoicedao')); @@ -1388,8 +1367,10 @@ if (!$error) { return 1; - } else return -1; - } else return -1; + } + else return -1; + } + else return -1; } /** @@ -1400,13 +1381,13 @@ * @param int $max Maxlength of 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 $addlinktonotes 1=Add link to notes - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @param string $target Target of link ('', '_self', '_blank', '_parent', '_backoffice', ...) + * @param int $notooltip 1=Disable tooltip + * @param int $addlinktonotes 1=Add link to notes + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @param string $target Target of link ('', '_self', '_blank', '_parent', '_backoffice', ...) * @return string String with URL */ - public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '') + public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '') { global $langs, $conf, $user, $mysoc; @@ -1417,8 +1398,8 @@ if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id; else $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id; - if (!$user->rights->facture->lire) - $option = 'nolink'; + if (!$user->rights->facture->lire) + $option = 'nolink'; if ($option !== 'nolink') { @@ -1434,56 +1415,56 @@ if ($this->type == self::TYPE_REPLACEMENT) $picto .= 'r'; // Replacement invoice if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note if ($this->type == self::TYPE_DEPOSIT) $picto .= 'd'; // Deposit invoice - $label = ''; - - if ($user->rights->facture->lire) { - $label = img_picto('', $picto).' '.$langs->trans("Invoice").''; - if ($this->type == self::TYPE_REPLACEMENT) $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("ReplacementInvoice").''; - if ($this->type == self::TYPE_CREDIT_NOTE) $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("CreditNote").''; - if ($this->type == self::TYPE_DEPOSIT) $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("Deposit").''; - if ($this->type == self::TYPE_SITUATION) $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("InvoiceSituation").''; - if (isset($this->statut) && isset($this->alreadypaid)) { - $label .= ' '.$this->getLibStatut(5, $this->alreadypaid); - } - if (!empty($this->ref)) - $label .= '
'.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->ref_client)) - $label .= '
'.$langs->trans('RefCustomer').': '.$this->ref_client; - if (!empty($this->date)) - $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); - 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('AmountVAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) // We keep test != 0 because $this->total_localtax1 can be '0.00000000' - $label .= '
'.$langs->transcountry('AmountLT1', $mysoc->country_code).': '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) - $label .= '
'.$langs->transcountry('AmountLT2', $mysoc->country_code).': '.price($this->total_localtax2, 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; - } + $label = ''; + + if ($user->rights->facture->lire) { + $label = ''.$langs->trans("Invoice").''; + if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("ReplacementInvoice").''; + if ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").''; + if ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").''; + if ($this->type == self::TYPE_SITUATION) $label = ''.$langs->transnoentitiesnoconv("InvoiceSituation").''; + if (!empty($this->ref)) + $label .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->ref_client)) + $label .= '
'.$langs->trans('RefCustomer').': '.$this->ref_client; + if (!empty($this->date)) + $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); + 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('AmountVAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) // We keep test != 0 because $this->total_localtax1 can be '0.00000000' + $label .= '
'.$langs->transcountry('AmountLT1', $mysoc->country_code).': '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) + $label .= '
'.$langs->transcountry('AmountLT2', $mysoc->country_code).': '.price($this->total_localtax2, 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 (isset($this->statut) && isset($this->alreadypaid)) { + $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5, $this->alreadypaid); + } + } $linkclose = ($target ? ' target="'.$target.'"' : ''); if (empty($notooltip) && $user->rights->facture->lire) { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("Invoice"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; - } - - $linkstart = ''; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("Invoice"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; + } + + $linkstart = ''; $linkend = ''; - if ($option == 'nolink') { - $linkstart = ''; - $linkend = ''; - } + if ($option == 'nolink') { + $linkstart = ''; + $linkend = ''; + } $result .= $linkstart; if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); @@ -1492,19 +1473,19 @@ if ($addlinktonotes) { - $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { - //$notetoshow = $langs->trans("ViewPrivateNote").':
'.dol_string_nohtmltag($txttoshow, 1); - $notetoshow = $langs->trans("ViewPrivateNote").':
'.$txttoshow; - $result .= ' '; - $result .= ''; - $result .= img_picto('', 'note'); - $result .= ''; - //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); - //$result.=''; - $result .= ''; - } + $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); + if ($txttoshow) + { + //$notetoshow = $langs->trans("ViewPrivateNote").':
'.dol_string_nohtmltag($txttoshow, 1); + $notetoshow = $langs->trans("ViewPrivateNote").':
'.$txttoshow; + $result .= ' '; + $result .= ''; + $result .= img_picto('', 'note'); + $result .= ''; + //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); + //$result.=''; + $result .= ''; + } } return $result; @@ -1542,10 +1523,10 @@ $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc"; $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc'; - $sql .= ', f.fk_incoterms, f.location_incoterms'; - $sql .= ', f.module_source, f.pos_source'; - $sql .= ", i.libelle as label_incoterms"; - $sql .= ", f.retained_warranty as retained_warranty, f.retained_warranty_date_limit as retained_warranty_date_limit, f.retained_warranty_fk_cond_reglement as retained_warranty_fk_cond_reglement"; + $sql .= ', f.fk_incoterms, f.location_incoterms'; + $sql .= ', f.module_source, f.pos_source'; + $sql .= ", i.libelle as label_incoterms"; + $sql .= ", f.retained_warranty as retained_warranty, f.retained_warranty_date_limit as retained_warranty_date_limit, f.retained_warranty_fk_cond_reglement as retained_warranty_fk_cond_reglement"; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; @@ -1573,6 +1554,7 @@ $this->ref = $obj->ref; $this->ref_client = $obj->ref_client; $this->ref_ext = $obj->ref_ext; + $this->ref_int = $obj->ref_int; $this->type = $obj->type; $this->date = $this->db->jdate($obj->df); $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax); @@ -1599,8 +1581,6 @@ $this->project = null; // Clear if another value was already set by fetch_projet $this->statut = $obj->fk_statut; - $this->status = $obj->fk_statut; - $this->date_lim_reglement = $this->db->jdate($obj->dlr); $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; @@ -1615,12 +1595,9 @@ $this->note = $obj->note_private; // deprecated $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; - $this->user_author = $obj->fk_user_author; // deprecated - $this->user_valid = $obj->fk_user_valid; // deprecated - $this->fk_user_author = $obj->fk_user_author; - $this->fk_user_valid = $obj->fk_user_valid; - $this->model_pdf = $obj->model_pdf; - $this->modelpdf = $obj->model_pdf; // deprecated + $this->user_author = $obj->fk_user_author; + $this->user_valid = $obj->fk_user_valid; + $this->modelpdf = $obj->model_pdf; $this->last_main_doc = $obj->last_main_doc; $this->situation_cycle_ref = $obj->situation_cycle_ref; $this->situation_counter = $obj->situation_counter; @@ -1654,7 +1631,7 @@ if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; - // Retrieve all extrafield + // Retreive all extrafield // fetch optionals attributes and labels $this->fetch_optionals(); @@ -1668,19 +1645,23 @@ return -3; } return 1; - } else { + } + else + { $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found'; dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR); return 0; } - } else { + } + else + { $this->error = $this->db->error(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load all detailed lines into this->lines * @@ -1692,11 +1673,11 @@ public function fetch_lines($only_product = 0, $loadalsotranslation = 0) { global $langs, $conf; - // phpcs:enable + // phpcs:enable $this->lines = array(); $sql = 'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; - $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice, l.ref_ext,'; + $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,'; $sql .= ' l.situation_percent, l.fk_prev_id,'; $sql .= ' l.rang, l.special_code,'; $sql .= ' l.date_start as date_start, l.date_end as date_end,'; @@ -1735,9 +1716,8 @@ $line->fk_product_type = $objp->fk_product_type; // Type of product $line->qty = $objp->qty; $line->subprice = $objp->subprice; - $line->ref_ext = $objp->ref_ext; // line external ref - - $line->vat_src_code = $objp->vat_src_code; + + $line->vat_src_code = $objp->vat_src_code; $line->tva_tx = $objp->tva_tx; $line->localtax1_tx = $objp->localtax1_tx; $line->localtax2_tx = $objp->localtax2_tx; @@ -1780,14 +1760,14 @@ $line->multicurrency_total_tva = $objp->multicurrency_total_tva; $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc; - $line->fetch_optionals(); + $line->fetch_optionals(); // multilangs - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) { - $line = new Product($this->db); - $line->fetch($objp->fk_product); - $line->getMultiLangs(); - } + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) { + $line = new Product($this->db); + $line->fetch($objp->fk_product); + $line->getMultiLangs(); + } $this->lines[$i] = $line; @@ -1795,7 +1775,9 @@ } $this->db->free($result); return 1; - } else { + } + else + { $this->error = $this->db->error(); return -3; } @@ -1807,7 +1789,7 @@ * * @return void */ - public function fetchPreviousNextSituationInvoice() + public function fetchPreviousNextSituationInvoice() { global $conf; @@ -1829,13 +1811,15 @@ $invoice = new Facture($this->db); if ($invoice->fetch($objp->rowid) > 0) { - if ($objp->situation_counter < $this->situation_counter - || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes - ) + if ($objp->situation_counter < $this->situation_counter + || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes + ) { - $this->tab_previous_situation_invoice[] = $invoice; - } else { - $this->tab_next_situation_invoice[] = $invoice; + $this->tab_previous_situation_invoice[] = $invoice; + } + else + { + $this->tab_next_situation_invoice[] = $invoice; } } } @@ -1849,7 +1833,7 @@ * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - public function update(User $user, $notrigger = 0) + public function update(User $user, $notrigger = 0) { global $conf; @@ -1858,7 +1842,6 @@ // Clean parameters if (empty($this->type)) $this->type = self::TYPE_STANDARD; if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->ref_ext)) $this->ref_ext = trim($this->ref_ext); if (isset($this->ref_client)) $this->ref_client = trim($this->ref_client); if (isset($this->increment)) $this->increment = trim($this->increment); if (isset($this->close_code)) $this->close_code = trim($this->close_code); @@ -1866,7 +1849,7 @@ if (isset($this->note) || isset($this->note_private)) $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated if (isset($this->note) || isset($this->note_private)) $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note)); if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); + if (isset($this->modelpdf)) $this->modelpdf = trim($this->modelpdf); if (isset($this->import_key)) $this->import_key = trim($this->import_key); if (isset($this->retained_warranty)) $this->retained_warranty = floatval($this->retained_warranty); @@ -1877,7 +1860,6 @@ // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET"; $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").","; - $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").","; $sql .= " type=".(isset($this->type) ? $this->db->escape($this->type) : "null").","; $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").","; $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").","; @@ -1907,7 +1889,7 @@ $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').","; $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").","; $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").","; - $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").","; + $sql .= " model_pdf=".(isset($this->modelpdf) ? "'".$this->db->escape($this->modelpdf)."'" : "null").","; $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").","; $sql .= " situation_cycle_ref=".(empty($this->situation_cycle_ref) ? "null" : $this->db->escape($this->situation_cycle_ref)).","; $sql .= " situation_counter=".(empty($this->situation_counter) ? "null" : $this->db->escape($this->situation_counter)).","; @@ -1952,23 +1934,25 @@ } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return 1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount) * * @param int $idremise Id of absolute discount * @return int >0 if OK, <0 if KO */ - public function insert_discount($idremise) + public function insert_discount($idremise) { - // phpcs:enable + // phpcs:enable global $langs; include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -2004,12 +1988,12 @@ // Get buy/cost price of invoice that is source of discount if ($remise->fk_facture_source > 0) { - $srcinvoice = new Facture($this->db); - $srcinvoice->fetch($remise->fk_facture_source); - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject - $formmargin = new FormMargin($this->db); - $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false); - $facligne->pa_ht = $arraytmp['pa_total']; + $srcinvoice = new Facture($this->db); + $srcinvoice->fetch($remise->fk_facture_source); + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject + $formmargin = new FormMargin($this->db); + $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false); + $facligne->pa_ht = $arraytmp['pa_total']; } $facligne->total_ht = -$remise->amount_ht; @@ -2038,23 +2022,29 @@ $this->db->commit(); return 1; - } else { + } + else + { $this->error = $facligne->error; $this->db->rollback(); return -1; } - } else { + } + else + { $this->error = $facligne->error; $this->db->rollback(); return -2; } - } else { + } + else + { $this->db->rollback(); return -3; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set customer ref * @@ -2062,10 +2052,10 @@ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - public function set_ref_client($ref_client, $notrigger = 0) + public function set_ref_client($ref_client, $notrigger = 0) { - // phpcs:enable - global $user; + // phpcs:enable + global $user; $error = 0; @@ -2074,7 +2064,8 @@ $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture'; if (empty($ref_client)) $sql .= ' SET ref_client = NULL'; - else $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\''; + else + $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\''; $sql .= ' WHERE rowid = '.$this->id; dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG); @@ -2104,7 +2095,9 @@ $this->db->commit(); return 1; - } else { + } + else + { foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); @@ -2123,14 +2116,14 @@ * @param int $idwarehouse Id warehouse to use for stock change. * @return int <0 if KO, 0=Refused, >0 if OK */ - public function delete($user, $notrigger = 0, $idwarehouse = -1) + public function delete($user, $notrigger = 0, $idwarehouse = -1) { global $langs, $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $rowid = $this->id; - dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG); + dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".$this->thirdparty->name, LOG_DEBUG); // Test to avoid invoice deletion (allowed if draft) $result = $this->is_erasable(); @@ -2143,10 +2136,10 @@ if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('BILL_DELETE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_DELETE', $user); + if ($result < 0) $error++; + // End call triggers } // Removed extrafields @@ -2193,7 +2186,6 @@ if (!$this->db->query($sql)) { $this->error = $this->db->error()." sql=".$sql; - $this->errors[] = $this->error; $this->db->rollback(); return -5; } @@ -2219,7 +2211,7 @@ } } - // Invoice line extrafileds + // Invoice line extrafileds $main = MAIN_DB_PREFIX.'facturedet'; $ef = $main."_extrafields"; $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture = $rowid)"; @@ -2237,9 +2229,6 @@ $resql = $this->db->query($sql); if ($resql) { - // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive - $this->deleteEcmFiles(); - // On efface le repertoire de pdf provisoire $ref = dol_sanitizeFileName($this->ref); if ($conf->facture->dir_output && !empty($this->ref)) @@ -2254,7 +2243,6 @@ { $langs->load("errors"); $this->error = $langs->trans("ErrorFailToDeleteFile", $file); - $this->errors[] = $this->error; $this->db->rollback(); return 0; } @@ -2265,7 +2253,6 @@ { $langs->load("errors"); $this->error = $langs->trans("ErrorFailToDeleteDir", $dir); - $this->errors[] = $this->error; $this->db->rollback(); return 0; } @@ -2274,25 +2261,29 @@ $this->db->commit(); return 1; - } else { + } + else + { $this->error = $this->db->lasterror()." sql=".$sql; - $this->errors[] = $this->error; $this->db->rollback(); return -6; } - } else { + } + else + { $this->error = $this->db->lasterror()." sql=".$sql; - $this->errors[] = $this->error; $this->db->rollback(); return -4; } - } else { + } + else + { $this->db->rollback(); return -2; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2, this->paye=1 * or partialy (if close_code filled) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0 @@ -2302,9 +2293,9 @@ * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple) * @return int <0 if KO, >0 if OK */ - public function set_paid($user, $close_code = '', $close_note = '') + public function set_paid($user, $close_code = '', $close_note = '') { - // phpcs:enable + // phpcs:enable $error = 0; if ($this->paye != 1) @@ -2327,11 +2318,13 @@ $resql = $this->db->query($sql); if ($resql) { - // Call trigger - $result = $this->call_trigger('BILL_PAYED', $user); - if ($result < 0) $error++; - // End call triggers - } else { + // Call trigger + $result = $this->call_trigger('BILL_PAYED', $user); + if ($result < 0) $error++; + // End call triggers + } + else + { $error++; $this->error = $this->db->lasterror(); } @@ -2340,17 +2333,21 @@ { $this->db->commit(); return 1; - } else { + } + else + { $this->db->rollback(); return -1; } - } else { + } + else + { return 0; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED * Fonction utilisee quand un paiement prelevement est refuse, @@ -2359,9 +2356,9 @@ * @param User $user Object user that change status * @return int <0 if KO, >0 if OK */ - public function set_unpaid($user) + public function set_unpaid($user) { - // phpcs:enable + // phpcs:enable $error = 0; $this->db->begin(); @@ -2376,11 +2373,13 @@ $resql = $this->db->query($sql); if ($resql) { - // Call trigger - $result = $this->call_trigger('BILL_UNPAYED', $user); - if ($result < 0) $error++; - // End call triggers - } else { + // Call trigger + $result = $this->call_trigger('BILL_UNPAYED', $user); + if ($result < 0) $error++; + // End call triggers + } + else + { $error++; $this->error = $this->db->error(); dol_print_error($this->db); @@ -2390,14 +2389,16 @@ { $this->db->commit(); return 1; - } else { + } + else + { $this->db->rollback(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never received) + call trigger BILL_CANCEL * Warning, if option to decrease stock on invoice was set, this function does not change stock (it might be a cancel because @@ -2408,9 +2409,9 @@ * @param string $close_note Comment * @return int <0 if KO, >0 if OK */ - public function set_canceled($user, $close_code = '', $close_note = '') + public function set_canceled($user, $close_code = '', $close_note = '') { - // phpcs:enable + // phpcs:enable dol_syslog(get_class($this)."::set_canceled rowid=".$this->id, LOG_DEBUG); @@ -2434,23 +2435,27 @@ $resql = $this->db->query($sql); if ($resql) { - // Call trigger - $result = $this->call_trigger('BILL_CANCEL', $user); - if ($result < 0) - { + // Call trigger + $result = $this->call_trigger('BILL_CANCEL', $user); + if ($result < 0) + { $this->db->rollback(); return -1; } - // End call triggers + // End call triggers $this->db->commit(); return 1; - } else { + } + else + { $this->error = $this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } - } else { + } + else + { $this->error = $this->db->error()." sql=".$sql; $this->db->rollback(); return -2; @@ -2465,14 +2470,14 @@ * @param string $force_number Reference to force on invoice * @param int $idwarehouse Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease) * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @param int $batch_rule 0=do not decrement batch, else batch rule to use, 1=take in batches ordered by sellby and eatby dates - * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK - */ - public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0) + * @param int $batch_rule [=0] 0 not decrement batch, else batch rule to use + * 1=take in batches ordered by sellby and eatby dates + * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK + */ + public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0) { global $conf, $langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $productStatic = null; $warehouseStatic = null; if ($batch_rule > 0) { @@ -2500,12 +2505,12 @@ } if (count($this->lines) <= 0) { - $langs->load("errors"); + $langs->load("errors"); $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); return -1; } if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) { $this->error = 'Permission denied'; dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR); @@ -2515,9 +2520,9 @@ $this->db->begin(); // Check parameters - if ($this->type == self::TYPE_REPLACEMENT) // if this is a replacement invoice - { - // Check that source invoice is known + if ($this->type == self::TYPE_REPLACEMENT) // si facture de remplacement + { + // Controle que facture source connue if ($this->fk_facture_source <= 0) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement")); @@ -2525,7 +2530,7 @@ return -10; } - // Load source invoice that has been replaced + // Charge la facture source a remplacer $facreplaced = new Facture($this->db); $result = $facreplaced->fetch($this->fk_facture_source); if ($result <= 0) @@ -2535,7 +2540,7 @@ return -11; } - // Check that source invoice not already replaced by another one. + // Controle que facture source non deja remplacee par une autre $idreplacement = $facreplaced->getIdReplacingInvoice('validated'); if ($idreplacement && $idreplacement != $this->id) { @@ -2559,7 +2564,8 @@ if ($force_number) { $num = $force_number; - } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life + } + elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life { if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date { @@ -2567,7 +2573,9 @@ $this->date_lim_reglement = $this->calculate_date_lim_reglement(); } $num = $this->getNextNumRef($this->thirdparty); - } else { + } + else + { $num = $this->ref; } $this->newref = dol_sanitizeFileName($num); @@ -2717,10 +2725,10 @@ // Trigger calls if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('BILL_VALIDATE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_VALIDATE', $user); + if ($result < 0) $error++; + // End call triggers } if (!$error) @@ -2748,16 +2756,16 @@ if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); - // Rename docs starting with $oldref with $newref - $listoffiles = dol_dir_list($conf->facture->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); - } + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->facture->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); + } } } } @@ -2781,22 +2789,24 @@ $this->date_validation = $now; $i = 0; - if (!empty($conf->global->INVOICE_USE_SITUATION)) - { - $final = true; - $nboflines = count($this->lines); - while (($i < $nboflines) && $final) { - $final = ($this->lines[$i]->situation_percent == 100); - $i++; - } - - if (empty($final)) $this->situation_final = 0; - else $this->situation_final = 1; - - $this->setFinal($user); - } - } - } else { + if (!empty($conf->global->INVOICE_USE_SITUATION)) + { + $final = true; + $nboflines = count($this->lines); + while (($i < $nboflines) && $final) { + $final = ($this->lines[$i]->situation_percent == 100); + $i++; + } + + if (empty($final)) $this->situation_final = 0; + else $this->situation_final = 1; + + $this->setFinal($user); + } + } + } + else + { $error++; } @@ -2804,7 +2814,9 @@ { $this->db->commit(); return 1; - } else { + } + else + { $this->db->rollback(); return -1; } @@ -2816,7 +2828,7 @@ * @param Translate $langs Translate object * @return bool false if KO, true if OK */ - public function updatePriceNextInvoice(&$langs) + public function updatePriceNextInvoice(&$langs) { foreach ($this->tab_next_situation_invoice as $next_invoice) { @@ -2860,7 +2872,7 @@ */ public function setDraft($user, $idwarehouse = -1) { - // phpcs:enable + // phpcs:enable global $conf, $langs; $error = 0; @@ -2931,11 +2943,15 @@ { $this->db->commit(); return 1; - } else { + } + else + { $this->db->rollback(); return -1; } - } else { + } + else + { $this->error = $this->db->error(); $this->db->rollback(); return -1; @@ -2978,42 +2994,40 @@ * @param int $situation_percent Situation advance percentage * @param int $fk_prev_id Previous situation line id reference * @param string $fk_unit Code of the unit to use. Null to use the default one - * @param double $pu_ht_devise Unit price in foreign currency - * @param string $ref_ext External reference of the line + * @param double $pu_ht_devise Unit price in currency * @return int <0 if KO, Id of line if OK */ - public function addline( - $desc, - $pu_ht, - $qty, - $txtva, - $txlocaltax1 = 0, - $txlocaltax2 = 0, - $fk_product = 0, - $remise_percent = 0, - $date_start = '', - $date_end = '', - $ventil = 0, - $info_bits = 0, - $fk_remise_except = '', - $price_base_type = 'HT', - $pu_ttc = 0, - $type = self::TYPE_STANDARD, - $rang = -1, - $special_code = 0, - $origin = '', - $origin_id = 0, - $fk_parent_line = 0, - $fk_fournprice = null, - $pa_ht = 0, - $label = '', - $array_options = 0, - $situation_percent = 100, - $fk_prev_id = 0, - $fk_unit = null, - $pu_ht_devise = 0, - $ref_ext = '' - ) { + public function addline( + $desc, + $pu_ht, + $qty, + $txtva, + $txlocaltax1 = 0, + $txlocaltax2 = 0, + $fk_product = 0, + $remise_percent = 0, + $date_start = '', + $date_end = '', + $ventil = 0, + $info_bits = 0, + $fk_remise_except = '', + $price_base_type = 'HT', + $pu_ttc = 0, + $type = self::TYPE_STANDARD, + $rang = -1, + $special_code = 0, + $origin = '', + $origin_id = 0, + $fk_parent_line = 0, + $fk_fournprice = null, + $pa_ht = 0, + $label = '', + $array_options = 0, + $situation_percent = 100, + $fk_prev_id = 0, + $fk_unit = null, + $pu_ht_devise = 0 + ) { // Deprecation warning if ($label) { dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING); @@ -3040,7 +3054,6 @@ if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; if (empty($fk_prev_id)) $fk_prev_id = 'null'; if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100; - if (empty($ref_ext)) $ref_ext = ''; $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -3057,7 +3070,9 @@ if ($price_base_type == 'HT') { $pu = $pu_ht; - } else { + } + else + { $pu = $pu_ttc; } @@ -3080,8 +3095,8 @@ $product_type = $product->type; if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) { - $langs->load("errors"); - $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); + $langs->load("errors"); + $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); $this->db->rollback(); return -3; } @@ -3114,8 +3129,8 @@ // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; // Rank to use @@ -3134,7 +3149,6 @@ $this->line->fk_facture = $this->id; $this->line->label = $label; // deprecated $this->line->desc = $desc; - $this->line->ref_ext = $ref_ext; $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise @@ -3143,8 +3157,8 @@ $this->line->tva_tx = $txtva; $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0); $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0); - $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]; - $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]; + $this->line->localtax1_type = $localtaxes_type[0]; + $this->line->localtax2_type = $localtaxes_type[2]; $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc); // For credit note and if qty is negative, total is negative @@ -3179,8 +3193,8 @@ $this->line->multicurrency_code = $this->multicurrency_code; $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; if (is_array($array_options) && count($array_options) > 0) { $this->line->array_options = $array_options; @@ -3199,19 +3213,24 @@ { $this->db->commit(); return $this->line->id; - } else { + } + else + { $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } - } else { + } + else + { $this->error = $this->line->error; - $this->errors = $this->line->errors; $this->db->rollback(); return -2; } - } else { - dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR); + } + else + { + dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR); return -3; } } @@ -3238,15 +3257,14 @@ * @param int $pa_ht Price (without tax) of product when it was bought * @param string $label Label of the line (deprecated, do not use) * @param int $special_code Special code (also used by externals modules!) - * @param array $array_options extrafields array + * @param array $array_options extrafields array * @param int $situation_percent Situation advance percentage * @param string $fk_unit Code of the unit to use. Null to use the default one * @param double $pu_ht_devise Unit price in currency * @param int $notrigger disable line update trigger - * @param string $ref_ext External reference of the line * @return int < 0 if KO, > 0 if OK */ - public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '') + public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0) { global $conf, $user; // Deprecation warning @@ -3284,16 +3302,13 @@ if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; if (empty($special_code) || $special_code == 3) $special_code = 0; if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100; - if (empty($ref_ext)) $ref_ext = ''; $remise_percent = price2num($remise_percent); $qty = price2num($qty); $pu = price2num($pu); - $pu_ht_devise = price2num($pu_ht_devise); + $pu_ht_devise = price2num($pu_ht_devise); $pa_ht = price2num($pa_ht); - if (!preg_match('/\((.*)\)/', $txtva)) { - $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' - } + $txtva = price2num($txtva); $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); @@ -3307,13 +3322,12 @@ $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); // Clean vat code - $reg = array(); - $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise); @@ -3328,8 +3342,8 @@ // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; // Old properties: $price, $remise (deprecated) @@ -3354,8 +3368,8 @@ $product_type = $product->type; if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) { - $langs->load("errors"); - $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); + $langs->load("errors"); + $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); $this->db->rollback(); return -3; } @@ -3365,7 +3379,7 @@ $line->oldline = $staticline; $this->line = $line; - $this->line->context = $this->context; + $this->line->context = $this->context; // Reorder if fk_parent_line change if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) @@ -3378,18 +3392,17 @@ $this->line->rowid = $rowid; $this->line->label = $label; $this->line->desc = $desc; - $this->line->ref_ext = $ref_ext; $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative $this->line->vat_src_code = $vat_src_code; $this->line->tva_tx = $txtva; $this->line->localtax1_tx = $txlocaltax1; $this->line->localtax2_tx = $txlocaltax2; - $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]; - $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]; + $this->line->localtax1_type = $localtaxes_type[0]; + $this->line->localtax2_type = $localtaxes_type[2]; $this->line->remise_percent = $remise_percent; - $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise + $this->line->subprice = ($this->type == 2 ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise $this->line->date_start = $date_start; $this->line->date_end = $date_end; $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative @@ -3409,10 +3422,10 @@ $this->line->pa_ht = $pa_ht; // Multicurrency - $this->line->multicurrency_subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht_devise) : $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise - $this->line->multicurrency_total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ht) : $multicurrency_total_ht); // For credit note and if qty is negative, total is negative - $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva); - $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc); + $this->line->multicurrency_subprice = $pu_ht_devise; + $this->line->multicurrency_total_ht = $multicurrency_total_ht; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; if (is_array($array_options) && count($array_options) > 0) { // We replace values in this->line->array_options only for entries defined into $array_options @@ -3431,12 +3444,16 @@ $this->update_price(1); $this->db->commit(); return $result; - } else { - $this->error = $this->line->error; + } + else + { + $this->error = $this->line->error; $this->db->rollback(); return -1; } - } else { + } + else + { $this->error = "Invoice statut makes operation forbidden"; return -2; } @@ -3449,7 +3466,7 @@ * @param float $situation_percent progress percentage need to be test * @return false if KO, true if OK */ - public function checkProgressLine($idline, $situation_percent) + public function checkProgressLine($idline, $situation_percent) { $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid) @@ -3469,7 +3486,7 @@ else return $situation_percent < $obj->situation_percent; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update invoice line with percentage * @@ -3477,16 +3494,16 @@ * @param int $percent Percentage * @return void */ - public function update_percent($line, $percent) + public function update_percent($line, $percent) { - // phpcs:enable - global $mysoc, $user; - - // Progress should never be changed for discount lines - if (($line->info_bits & 2) == 2) - { - return; - } + // phpcs:enable + global $mysoc, $user; + + // Progress should never be changed for discount lines + if (($line->info_bits & 2) == 2) + { + return; + } include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -3512,9 +3529,9 @@ * @param int $rowid Id of line to delete * @return int <0 if KO, >0 if OK */ - public function deleteline($rowid) + public function deleteline($rowid) { - global $user; + global $user; dol_syslog(get_class($this)."::deleteline rowid=".$rowid, LOG_DEBUG); @@ -3542,7 +3559,7 @@ $line = new FactureLigne($this->db); - $line->context = $this->context; + $line->context = $this->context; // For triggers $result = $line->fetch($rowid); @@ -3556,19 +3573,23 @@ { $this->db->commit(); return 1; - } else { + } + else + { $this->db->rollback(); $this->error = $this->db->lasterror(); return -1; } - } else { + } + else + { $this->db->rollback(); $this->error = $line->error; return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set percent discount * @@ -3577,9 +3598,9 @@ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if ko, >0 if ok */ - public function set_remise($user, $remise, $notrigger = 0) + public function set_remise($user, $remise, $notrigger = 0) { - // phpcs:enable + // phpcs:enable // Clean parameters if (empty($remise)) $remise = 0; @@ -3619,7 +3640,9 @@ $this->db->commit(); return 1; - } else { + } + else + { foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); @@ -3632,7 +3655,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set absolute discount * @@ -3641,9 +3664,9 @@ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - public function set_remise_absolue($user, $remise, $notrigger = 0) + public function set_remise_absolue($user, $remise, $notrigger = 0) { - // phpcs:enable + // phpcs:enable if (empty($remise)) $remise = 0; if ($user->rights->facture->creer) @@ -3686,7 +3709,9 @@ { $this->db->commit(); return 1; - } else { + } + else + { foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); @@ -3706,7 +3731,7 @@ * @param string $mode 'next' for next value or 'last' for last value * @return string free ref or last ref */ - public function getNextNumRef($soc, $mode = 'next') + public function getNextNumRef($soc, $mode = 'next') { global $conf, $langs; @@ -3804,7 +3829,7 @@ * @param int $id Id of object to load * @return void */ - public function info($id) + public function info($id) { $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,'; $sql .= ' date_closing as dateclosing,'; @@ -3844,13 +3869,15 @@ $this->date_closing = $this->db->jdate($obj->dateclosing); } $this->db->free($result); - } else { + } + else + { dol_print_error($this->db); } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of invoices (eventually filtered on a user) into an array * @@ -3864,9 +3891,9 @@ * @param string $sortorder Sort order * @return array|int -1 if KO, array with result if OK */ - public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC') + public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC') { - // phpcs:enable + // phpcs:enable global $conf, $user; $ga = array(); @@ -3902,10 +3929,13 @@ if ($shortlist == 1) { $ga[$obj->fid] = $obj->ref; - } elseif ($shortlist == 2) + } + elseif ($shortlist == 2) { $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')'; - } else { + } + else + { $ga[$i]['id'] = $obj->fid; $ga[$i]['ref'] = $obj->ref; $ga[$i]['name'] = $obj->name; @@ -3914,14 +3944,16 @@ } } return $ga; - } else { + } + else + { dol_print_error($this->db); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of invoices qualified to be replaced by another invoice. * Invoices matching the following rules are returned: @@ -3930,9 +3962,9 @@ * @param int $socid Id thirdparty * @return array|int Array of invoices ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1) */ - public function list_replacable_invoices($socid = 0) + public function list_replacable_invoices($socid = 0) { - // phpcs:enable + // phpcs:enable global $conf; $return = array(); @@ -3962,14 +3994,16 @@ } //print_r($return); return $return; - } else { + } + else + { $this->error = $this->db->error(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of invoices qualified to be corrected by a credit note. * Invoices matching the following rules are returned: @@ -3978,9 +4012,9 @@ * @param int $socid Id thirdparty * @return array Array of invoices ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>) */ - public function list_qualified_avoir_invoices($socid = 0) + public function list_qualified_avoir_invoices($socid = 0) { - // phpcs:enable + // phpcs:enable global $conf; $return = array(); @@ -3999,17 +4033,19 @@ $sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) { - // Select the last situation invoice - $sqlSit = 'SELECT MAX(fs.rowid)'; - $sqlSit .= " FROM ".MAIN_DB_PREFIX."facture as fs"; - $sqlSit .= " WHERE fs.entity IN (".getEntity('invoice').")"; - $sqlSit .= " AND fs.type = ".self::TYPE_SITUATION; - $sqlSit .= " AND fs.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")"; - $sqlSit .= " GROUP BY fs.situation_cycle_ref"; - $sqlSit .= " ORDER BY fs.situation_counter"; - $sql .= " AND ( f.type != ".self::TYPE_SITUATION." OR f.rowid IN (".$sqlSit.") )"; // Type non 5 si facture non avoir - } else { - $sql .= " AND f.type != ".self::TYPE_SITUATION; // Type non 5 si facture non avoir + // Select the last situation invoice + $sqlSit = 'SELECT MAX(fs.rowid)'; + $sqlSit .= " FROM ".MAIN_DB_PREFIX."facture as fs"; + $sqlSit .= " WHERE fs.entity IN (".getEntity('invoice').")"; + $sqlSit .= " AND fs.type = ".self::TYPE_SITUATION; + $sqlSit .= " AND fs.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")"; + $sqlSit .= " GROUP BY fs.situation_cycle_ref"; + $sqlSit .= " ORDER BY fs.situation_counter"; + $sql .= " AND ( f.type != ".self::TYPE_SITUATION." OR f.rowid IN (".$sqlSit.") )"; // Type non 5 si facture non avoir + } + else + { + $sql .= " AND f.type != ".self::TYPE_SITUATION; // Type non 5 si facture non avoir } if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; @@ -4033,23 +4069,25 @@ } return $return; - } else { + } + else + { $this->error = $this->db->error(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * * @param User $user Object user * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK */ - public function load_board($user) + public function load_board($user) { - // phpcs:enable + // phpcs:enable global $conf, $langs; $clause = " WHERE"; @@ -4097,7 +4135,9 @@ } return $response; - } else { + } + else + { dol_print_error($this->db); $this->error = $this->db->error(); return -1; @@ -4112,7 +4152,7 @@ * * @return array Liste des id contacts facturation */ - public function getIdBillingContact() + public function getIdBillingContact() { return $this->getIdContact('external', 'BILLING'); } @@ -4122,7 +4162,7 @@ * * @return array Liste des id contacts livraison */ - public function getIdShippingContact() + public function getIdShippingContact() { return $this->getIdContact('external', 'SHIPPING'); } @@ -4136,22 +4176,20 @@ * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines * @return void */ - public function initAsSpecimen($option = '') + public function initAsSpecimen($option = '') { - global $conf, $langs, $user; + global $conf, $langs; $now = dol_now(); $arraynow = dol_getdate($now); $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']); - // Load array of products prodids + // Load array of products prodids $num_prods = 0; $prodids = array(); $sql = "SELECT rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."product"; $sql .= " WHERE entity IN (".getEntity('product').")"; - $sql .= $this->db->plimit(100); - $resql = $this->db->query($sql); if ($resql) { @@ -4186,8 +4224,6 @@ $this->note_public = 'This is a comment (public)'; $this->note_private = 'This is a comment (private)'; $this->note = 'This is a comment (private)'; - - $this->fk_user_author = $user->id; $this->multicurrency_tx = 1; $this->multicurrency_code = $conf->currency; @@ -4221,7 +4257,8 @@ $line->multicurrency_total_ht = -200; $line->multicurrency_total_ttc = -239.2; $line->multicurrency_total_tva = -39.2; - } elseif ($xnbp == 2) // UP is negative (free line) + } + elseif ($xnbp == 2) // UP is negative (free line) { $line->subprice = -100; $line->total_ht = -100; @@ -4231,7 +4268,8 @@ $line->multicurrency_total_ht = -200; $line->multicurrency_total_ttc = -239.2; $line->multicurrency_total_tva = -39.2; - } elseif ($xnbp == 3) // Discount is 50% (product line) + } + elseif ($xnbp == 3) // Discount is 50% (product line) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; @@ -4242,7 +4280,8 @@ $line->multicurrency_total_ttc = 119.6; $line->multicurrency_total_tva = 19.6; $line->remise_percent = 50; - } else // (product line) + } + else // (product line) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; @@ -4293,15 +4332,15 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * * @return int <0 if KO, >0 if OK */ - public function load_state_board() + public function load_state_board() { - // phpcs:enable + // phpcs:enable global $conf, $user; $this->nb = array(); @@ -4326,9 +4365,11 @@ { $this->nb["invoices"] = $obj->nb; } - $this->db->free($resql); + $this->db->free($resql); return 1; - } else { + } + else + { dol_print_error($this->db); $this->error = $this->db->error(); return -1; @@ -4340,36 +4381,34 @@ * * @return int >0 if OK, <0 if KO */ - public function getLinesArray() + public function getLinesArray() { - return $this->fetch_lines(); + return $this->fetch_lines(); } /** * Create a document onto disk according to template module. * - * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model','alpha') for example. - * @param Translate $outputlangs Object lang to use for translation + * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf','alpha') for example. + * @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 + * @param null|array $moreparams Array to provide more information * @return int <0 if KO, >0 if OK */ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) { global $conf, $langs; - $outputlangs->loadLangs(array("bills", "products")); + $langs->load("bills"); if (!dol_strlen($modele)) { $modele = 'crabe'; $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type; - if (!empty($this->model_pdf)) { - $modele = $this->model_pdf; - } elseif (!empty($this->modelpdf)) { // deprecated + if ($this->modelpdf) { $modele = $this->modelpdf; } elseif (!empty($conf->global->$thisTypeConfName)) { $modele = $conf->global->$thisTypeConfName; @@ -4388,7 +4427,7 @@ * * @return int >= 1 if OK, -1 if error */ - public function newCycle() + public function newCycle() { $sql = 'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.'facture as f'; $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")"; @@ -4411,27 +4450,27 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Checks if the invoice is the first of a cycle * * @return boolean */ - public function is_first() + public function is_first() { - // phpcs:enable + // phpcs:enable return ($this->situation_counter == 1); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns an array containing the previous situations as Facture objects * * @return mixed -1 if error, array of previous situations */ - public function get_prev_sits() + public function get_prev_sits() { - // phpcs:enable + // phpcs:enable global $conf; $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture'; @@ -4463,7 +4502,7 @@ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - public function setFinal(User $user, $notrigger = 0) + public function setFinal(User $user, $notrigger = 0) { $error = 0; @@ -4491,7 +4530,9 @@ { $this->db->commit(); return 1; - } else { + } + else + { foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); @@ -4502,15 +4543,15 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Checks if the invoice is the last in its cycle * * @return bool Last of the cycle status */ - public function is_last_in_cycle() + public function is_last_in_cycle() { - // phpcs:enable + // phpcs:enable global $conf; if (!empty($this->situation_cycle_ref)) { @@ -4568,21 +4609,24 @@ $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay); if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) { - $totalpaye = $this->getSommePaiement(); - $totalpaye = floatval($totalpaye); - $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount(); - if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0) - { - if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) - { - $hasDelay = 1; - } elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) - { - $hasDelay = 1; - } else { - $hasDelay = 0; - } - } + $totalpaye = $this->getSommePaiement(); + $totalpaye = floatval($totalpaye); + $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount(); + if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0) + { + if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) + { + $hasDelay = 1; + } + elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) + { + $hasDelay = 1; + } + else + { + $hasDelay = 0; + } + } } return $hasDelay; @@ -4633,45 +4677,48 @@ public function getRetainedWarrantyAmount($rounding = -1) { global $conf; - if (empty($this->retained_warranty)) { - return -1; - } - - $retainedWarrantyAmount = 0; - - // Billed - retained warranty - if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) - { - $displayWarranty = true; - // Check if this situation invoice is 100% for real - if (!empty($this->lines)) { - foreach ($this->lines as $i => $line) { - if ($line->product_type < 2 && $line->situation_percent < 100) { - $displayWarranty = false; - break; - } - } - } - - if ($displayWarranty && !empty($this->situation_final)) - { - $this->fetchPreviousNextSituationInvoice(); - $TPreviousIncoice = $this->tab_previous_situation_invoice; - - $total2BillWT = 0; - foreach ($TPreviousIncoice as &$fac) { - $total2BillWT += $fac->total_ttc; - } - $total2BillWT += $this->total_ttc; - - $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100; - } else { - return -1; - } - } else { - // Because one day retained warranty could be used on standard invoices - $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100; - } + if (empty($this->retained_warranty)) { + return -1; + } + + $retainedWarrantyAmount = 0; + + // Billed - retained warranty + if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) + { + $displayWarranty = true; + // Check if this situation invoice is 100% for real + if (!empty($this->lines)) { + foreach ($this->lines as $i => $line) { + if ($line->product_type < 2 && $line->situation_percent < 100) { + $displayWarranty = false; + break; + } + } + } + + if ($displayWarranty && !empty($this->situation_final)) + { + $this->fetchPreviousNextSituationInvoice(); + $TPreviousIncoice = $this->tab_previous_situation_invoice; + + $total2BillWT = 0; + foreach ($TPreviousIncoice as &$fac) { + $total2BillWT += $fac->total_ttc; + } + $total2BillWT += $this->total_ttc; + + $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100; + } + else { + return -1; + } + } + else + { + // Because one day retained warranty could be used on standard invoices + $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100; + } if ($rounding < 0) { $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT); @@ -4681,7 +4728,7 @@ return round($retainedWarrantyAmount, $rounding); } - return $retainedWarrantyAmount; + return $retainedWarrantyAmount; } /** @@ -4692,28 +4739,32 @@ */ public function setRetainedWarranty($value) { - dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')'); - if ($this->statut >= 0) - { - $fieldname = 'retained_warranty'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.floatval($value); - $sql .= ' WHERE rowid='.$this->id; - - if ($this->db->query($sql)) - { - $this->retained_warranty = floatval($value); - return 1; - } else { - dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error()); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible'); - $this->error = 'Status of the object is incompatible '.$this->statut; - return -2; - } + dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')'); + if ($this->statut >= 0) + { + $fieldname = 'retained_warranty'; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.floatval($value); + $sql .= ' WHERE rowid='.$this->id; + + if ($this->db->query($sql)) + { + $this->retained_warranty = floatval($value); + return 1; + } + else + { + dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error()); + $this->error = $this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible'); + $this->error = 'Status of the object is incompatible '.$this->statut; + return -2; + } } @@ -4726,33 +4777,37 @@ */ public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = false) { - if (!$timestamp && $dateYmd) { - $timestamp = $this->db->jdate($dateYmd); - } - - - dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')'); - if ($this->statut >= 0) - { - $fieldname = 'retained_warranty_date_limit'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.(strval($timestamp) != '' ? '\''.$this->db->idate($timestamp).'\'' : 'null'); - $sql .= ' WHERE rowid='.$this->id; - - if ($this->db->query($sql)) - { - $this->retained_warranty_date_limit = $timestamp; - return 1; - } else { - dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error()); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible'); - $this->error = 'Status of the object is incompatible '.$this->statut; - return -2; - } + if (!$timestamp && $dateYmd) { + $timestamp = $this->db->jdate($dateYmd); + } + + + dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')'); + if ($this->statut >= 0) + { + $fieldname = 'retained_warranty_date_limit'; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.(strval($timestamp) != '' ? '\''.$this->db->idate($timestamp).'\'' : 'null'); + $sql .= ' WHERE rowid='.$this->id; + + if ($this->db->query($sql)) + { + $this->retained_warranty_date_limit = $timestamp; + return 1; + } + else + { + dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error()); + $this->error = $this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible'); + $this->error = 'Status of the object is incompatible '.$this->statut; + return -2; + } } } @@ -4762,12 +4817,12 @@ */ class FactureLigne extends CommonInvoiceLine { - /** + /** * @var string ID to identify managed object */ public $element = 'facturedet'; - /** + /** * @var string Name of table without prefix where object is stored */ public $table_element = 'facturedet'; @@ -4779,10 +4834,12 @@ public $fk_facture; //! Id parent line public $fk_parent_line; - + /** + * @deprecated + */ + public $label; //! Description ligne public $desc; - public $ref_ext; // External reference of the line public $localtax1_type; // Local tax 1 type public $localtax2_type; // Local tax 2 type @@ -4808,6 +4865,21 @@ public $date_start; public $date_end; + + // From llx_product + /** + * @deprecated + * @see $product_ref + */ + public $ref; // Product ref (deprecated) + public $product_ref; // Product ref + /** + * @deprecated + * @see $product_label + */ + public $libelle; // Product label (deprecated) + public $product_label; // Product label + public $product_desc; // Description produit public $skip_update_total; // Skip update price total for special lines @@ -4835,10 +4907,10 @@ * @param int $rowid id of invoice line to get * @return int <0 if KO, >0 if OK */ - public function fetch($rowid) + public function fetch($rowid) { $sql = 'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.label as custom_label, fd.description, fd.price, fd.qty, fd.vat_src_code, fd.tva_tx,'; - $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,'; + $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice,'; $sql .= ' fd.date_start as date_start, fd.date_end as date_end, fd.fk_product_fournisseur_price as fk_fournprice, fd.buy_price_ht as pa_ht,'; $sql .= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,'; $sql .= ' fd.fk_code_ventilation,'; @@ -4848,7 +4920,7 @@ $sql .= ' fd.multicurrency_total_ht,'; $sql .= ' fd.multicurrency_total_tva,'; $sql .= ' fd.multicurrency_total_ttc,'; - $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc'; + $sql .= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid'; $sql .= ' WHERE fd.rowid = '.$rowid; @@ -4866,7 +4938,6 @@ $this->desc = $objp->description; $this->qty = $objp->qty; $this->subprice = $objp->subprice; - $this->ref_ext = $objp->ref_ext; $this->vat_src_code = $objp->vat_src_code; $this->tva_tx = $objp->tva_tx; $this->localtax1_tx = $objp->localtax1_tx; @@ -4894,12 +4965,11 @@ $this->marque_tx = $marginInfos[2]; $this->ref = $objp->product_ref; // deprecated - $this->product_ref = $objp->product_ref; - $this->product_label = $objp->product_label; + $this->libelle = $objp->product_libelle; // deprecated + $this->product_label = $objp->product_libelle; $this->product_desc = $objp->product_desc; - - $this->fk_unit = $objp->fk_unit; + $this->fk_unit = $objp->fk_unit; $this->fk_user_modif = $objp->fk_user_modif; $this->fk_user_author = $objp->fk_user_author; @@ -4914,8 +4984,10 @@ $this->db->free($result); return 1; - } else { - $this->error = $this->db->lasterror(); + } + else + { + $this->error = $this->db->lasterror(); return -1; } } @@ -4927,15 +4999,15 @@ * @param int $noerrorifdiscountalreadylinked 1=Do not make error if lines is linked to a discount and discount already linked to another * @return int <0 if KO, >0 if OK */ - public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0) + public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0) { global $langs, $user, $conf; $error = 0; - $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. - - dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG); + $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. + + dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG); // Clean parameters $this->desc = trim($this->desc); @@ -4950,7 +5022,6 @@ if (empty($this->remise_percent)) $this->remise_percent = 0; if (empty($this->info_bits)) $this->info_bits = 0; if (empty($this->subprice)) $this->subprice = 0; - if (empty($this->ref_ext)) $this->ref_ext = ''; if (empty($this->special_code)) $this->special_code = 0; if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; if (empty($this->fk_prev_id)) $this->fk_prev_id = 0; @@ -4968,7 +5039,9 @@ if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; - } else { + } + else + { $this->pa_ht = $result; } } @@ -4997,7 +5070,7 @@ $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet'; $sql .= ' (fk_facture, fk_parent_line, label, description, qty,'; $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; - $sql .= ' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,'; + $sql .= ' fk_product, product_type, remise_percent, subprice, fk_remise_except,'; $sql .= ' date_start, date_end, fk_code_ventilation, '; $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,'; $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,'; @@ -5010,7 +5083,7 @@ $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; $sql .= " '".$this->db->escape($this->desc)."',"; $sql .= " ".price2num($this->qty).","; - $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; + $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; $sql .= " ".price2num($this->tva_tx).","; $sql .= " ".price2num($this->localtax1_tx).","; $sql .= " ".price2num($this->localtax2_tx).","; @@ -5020,7 +5093,6 @@ $sql .= " ".((int) $this->product_type).","; $sql .= " ".price2num($this->remise_percent).","; $sql .= " ".price2num($this->subprice).","; - $sql .= " '".$this->db->escape($this->ref_ext)."',"; $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").','; $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").","; $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").","; @@ -5055,14 +5127,14 @@ $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet'); $this->rowid = $this->id; // For backward compatibility - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } // Si fk_remise_except defini, on lie la remise a la facture // ce qui la flague comme "consommee". @@ -5075,17 +5147,19 @@ // Check if discount was found if ($result > 0) { - // Check if discount not already affected to another invoice + // Check if discount not already affected to another invoice if ($discount->fk_facture_line > 0) { - if (empty($noerrorifdiscountalreadylinked)) - { - $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id); - dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -3; - } - } else { + if (empty($noerrorifdiscountalreadylinked)) + { + $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id); + dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -3; + } + } + else + { $result = $discount->link_to_invoice($this->rowid, 0); if ($result < 0) { @@ -5095,13 +5169,17 @@ return -3; } } - } else { + } + else + { $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded"); dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); $this->db->rollback(); return -3; } - } else { + } + else + { $this->error = $discount->error; dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); $this->db->rollback(); @@ -5111,19 +5189,21 @@ if (!$notrigger) { - // Call trigger - $result = $this->call_trigger('LINEBILL_INSERT', $user); - if ($result < 0) - { + // Call trigger + $result = $this->call_trigger('LINEBILL_INSERT', $user); + if ($result < 0) + { $this->db->rollback(); return -2; } - // End call triggers + // End call triggers } $this->db->commit(); return $this->id; - } else { + } + else + { $this->error = $this->db->lasterror(); $this->db->rollback(); return -2; @@ -5137,7 +5217,7 @@ * @param int $notrigger Disable triggers * @return int <0 if KO, >0 if OK */ - public function update($user = '', $notrigger = 0) + public function update($user = '', $notrigger = 0) { global $user, $conf; @@ -5147,7 +5227,6 @@ // Clean parameters $this->desc = trim($this->desc); - if (empty($this->ref_ext)) $this->ref_ext = ''; if (empty($this->tva_tx)) $this->tva_tx = 0; if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; @@ -5177,42 +5256,43 @@ if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; - } else { + } + else + { $this->pa_ht = $result; } } $this->db->begin(); - // Update line in database - $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET"; - $sql .= " description='".$this->db->escape($this->desc)."'"; - $sql .= ", ref_ext='".$this->db->escape($this->ref_ext)."'"; - $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); - $sql .= ", subprice=".price2num($this->subprice).""; - $sql .= ", remise_percent=".price2num($this->remise_percent).""; - if ($this->fk_remise_except) $sql .= ", fk_remise_except=".$this->fk_remise_except; - else $sql .= ", fk_remise_except=null"; + // Mise a jour ligne en base + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET"; + $sql .= " description='".$this->db->escape($this->desc)."'"; + $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= ", subprice=".price2num($this->subprice).""; + $sql .= ", remise_percent=".price2num($this->remise_percent).""; + if ($this->fk_remise_except) $sql .= ", fk_remise_except=".$this->fk_remise_except; + else $sql .= ", fk_remise_except=null"; $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'"; - $sql .= ", tva_tx=".price2num($this->tva_tx).""; - $sql .= ", localtax1_tx=".price2num($this->localtax1_tx).""; - $sql .= ", localtax2_tx=".price2num($this->localtax2_tx).""; + $sql .= ", tva_tx=".price2num($this->tva_tx).""; + $sql .= ", localtax1_tx=".price2num($this->localtax1_tx).""; + $sql .= ", localtax2_tx=".price2num($this->localtax2_tx).""; $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql .= ", qty=".price2num($this->qty); - $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null"); - $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null"); - $sql .= ", product_type=".$this->product_type; - $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'"; - $sql .= ", special_code='".$this->db->escape($this->special_code)."'"; - if (empty($this->skip_update_total)) - { - $sql .= ", total_ht=".price2num($this->total_ht); - $sql .= ", total_tva=".price2num($this->total_tva); - $sql .= ", total_ttc=".price2num($this->total_ttc); - $sql .= ", total_localtax1=".price2num($this->total_localtax1); - $sql .= ", total_localtax2=".price2num($this->total_localtax2); - } + $sql .= ", qty=".price2num($this->qty); + $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null"); + $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null"); + $sql .= ", product_type=".$this->product_type; + $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'"; + $sql .= ", special_code='".$this->db->escape($this->special_code)."'"; + if (empty($this->skip_update_total)) + { + $sql .= ", total_ht=".price2num($this->total_ht); + $sql .= ", total_tva=".price2num($this->total_tva); + $sql .= ", total_ttc=".price2num($this->total_ttc); + $sql .= ", total_localtax1=".price2num($this->total_localtax1); + $sql .= ", total_localtax2=".price2num($this->total_localtax2); + } $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null"); $sql .= ", buy_price_ht='".price2num($this->pa_ht)."'"; $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null"); @@ -5223,9 +5303,9 @@ // Multicurrency $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; $sql .= " WHERE rowid = ".$this->rowid; @@ -5233,30 +5313,32 @@ $resql = $this->db->query($sql); if ($resql) { - if (!$error) - { - $this->id = $this->rowid; - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (!$error) + { + $this->id = $this->rowid; + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('LINEBILL_UPDATE', $user); - if ($result < 0) + // Call trigger + $result = $this->call_trigger('LINEBILL_UPDATE', $user); + if ($result < 0) { $this->db->rollback(); return -2; } - // End call triggers + // End call triggers } $this->db->commit(); return 1; - } else { + } + else + { $this->error = $this->db->error(); $this->db->rollback(); return -2; @@ -5266,10 +5348,10 @@ /** * Delete line in database * TODO Add param User $user and notrigger (see skeleton) - * + * * @return int <0 if KO, >0 if OK */ - public function delete() + public function delete() { global $user; @@ -5284,13 +5366,13 @@ } // End call triggers - // extrafields - $result = $this->deleteExtraFields(); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } + // extrafields + $result = $this->deleteExtraFields(); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".$this->rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); @@ -5298,23 +5380,25 @@ { $this->db->commit(); return 1; - } else { + } + else + { $this->error = $this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Update DB line fields total_xxx + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update DB line fields total_xxx * Used by migration * * @return int <0 if KO, >0 if OK */ - public function update_total() + public function update_total() { - // phpcs:enable + // phpcs:enable $this->db->begin(); dol_syslog(get_class($this)."::update_total", LOG_DEBUG); @@ -5338,14 +5422,16 @@ { $this->db->commit(); return 1; - } else { + } + else + { $this->error = $this->db->error(); $this->db->rollback(); return -2; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns situation_percent of the previous line. * Warning: If invoice is a replacement invoice, this->fk_prev_id is id of the replaced line. @@ -5354,14 +5440,14 @@ * @param bool $include_credit_note Include credit note or not * @return int >= 0 */ - public function get_prev_progress($invoiceid, $include_credit_note = true) + public function get_prev_progress($invoiceid, $include_credit_note = true) { - // phpcs:enable + // phpcs:enable global $invoicecache; if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") { return 0; } else { - // If invoice is not a situation invoice, this->fk_prev_id is used for something else + // If invoice is not a situation invoice, this->fk_prev_id is used for something else if (!isset($invoicecache[$invoiceid])) { $invoicecache[$invoiceid] = new Facture($this->db); $invoicecache[$invoiceid]->fetch($invoiceid); @@ -5376,20 +5462,20 @@ $returnPercent = floatval($res['situation_percent']); if ($include_credit_note) { - $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd'; - $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) '; - $sql .= ' WHERE fd.fk_prev_id ='.$this->fk_prev_id; - $sql .= ' AND f.situation_cycle_ref = '.$invoicecache[$invoiceid]->situation_cycle_ref; // Prevent cycle outed - $sql .= ' AND f.type = '.Facture::TYPE_CREDIT_NOTE; - - $res = $this->db->query($sql); - if ($res) { - while ($obj = $this->db->fetch_object($res)) { - $returnPercent = $returnPercent + floatval($obj->situation_percent); - } - } else { - dol_print_error($this->db); - } + $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd'; + $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) '; + $sql .= ' WHERE fd.fk_prev_id ='.$this->fk_prev_id; + $sql .= ' AND f.situation_cycle_ref = '.$invoicecache[$invoiceid]->situation_cycle_ref; // Prevent cycle outed + $sql .= ' AND f.type = '.Facture::TYPE_CREDIT_NOTE; + + $res = $this->db->query($sql); + if ($res) { + while ($obj = $this->db->fetch_object($res)) { + $returnPercent = $returnPercent + floatval($obj->situation_percent); + } + } else { + dol_print_error($this->db); + } } return $returnPercent; --- /tmp/dsg/dolibarr/htdocs/compta/facture/class/github_facturestats.class.php +++ /tmp/dsg/dolibarr/htdocs/compta/facture/class/client_facturestats.class.php @@ -33,39 +33,39 @@ */ class FactureStats extends Stats { - public $socid; - public $userid; - - /** + public $socid; + public $userid; + + /** * @var string Name of table without prefix where object is stored */ public $table_element; - public $from; - public $field; - public $where; - public $join; - - - /** - * Constructor - * + public $from; + public $field; + public $where; + public $join; + + + /** + * Constructor + * * @param DoliDB $db Database handler * @param int $socid Id third party for filter. This value must be forced during the new to external user company if user is an external user. * @param string $mode Option ('customer', 'supplier') - * @param int $userid Id user for filter (creation user) - * @param int $typentid Id typent of thirdpary for filter - * @param int $categid Id category of thirdpary for filter + * @param int $userid Id user for filter (creation user) + * @param int $typentid Id typent of thirdpary for filter + * @param int $categid Id category of thirdpary for filter */ public function __construct($db, $socid, $mode, $userid = 0, $typentid = 0, $categid = 0) { global $user, $conf; $this->db = $db; - $this->socid = ($socid > 0 ? $socid : 0); - $this->userid = $userid; + $this->socid = ($socid > 0 ? $socid : 0); + $this->userid = $userid; $this->cachefilesuffix = $mode; - $this->join = ''; + $this->join = ''; if ($mode == 'customer') { @@ -93,22 +93,22 @@ { $this->where .= " AND f.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where .= ' AND f.fk_user_author = '.$this->userid; + if ($this->userid > 0) $this->where .= ' AND f.fk_user_author = '.$this->userid; if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $this->where .= " AND f.type IN (0,1,2,5)"; else $this->where .= " AND f.type IN (0,1,2,3,5)"; - if ($typentid) - { - $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = f.fk_soc'; - $this->where .= ' AND s.fk_typent = '.$typentid; - } - - if ($categid) - { - $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_societe as cs ON cs.fk_soc = f.fk_soc'; - $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie as c ON c.rowid = cs.fk_categorie'; - $this->where .= ' AND c.rowid = '.$categid; - } + if ($typentid) + { + $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = f.fk_soc'; + $this->where .= ' AND s.fk_typent = '.$typentid; + } + + if ($categid) + { + $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_societe as cs ON cs.fk_soc = f.fk_soc'; + $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie as c ON c.rowid = cs.fk_categorie'; + $this->where .= ' AND c.rowid = '.$categid; + } } @@ -116,7 +116,7 @@ * Return orders number by month for a year * * @param int $year Year to scan - * @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 * @return array Array of values */ public function getNbByMonth($year, $format = 0) @@ -126,11 +126,11 @@ $sql = "SELECT date_format(f.datef,'%m') as dm, COUNT(*) as nb"; $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= $this->join; + $sql .= $this->join; $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; - $sql .= $this->db->order('dm', 'DESC'); + $sql .= $this->db->order('dm', 'DESC'); $res = $this->_getNbByMonth($year, $sql, $format); //var_dump($res);print '
'; @@ -150,10 +150,10 @@ $sql = "SELECT date_format(f.datef,'%Y') as dm, COUNT(*), SUM(c.".$this->field.")"; $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= $this->join; + $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " GROUP BY dm"; - $sql .= $this->db->order('dm', 'DESC'); + $sql .= $this->db->order('dm', 'DESC'); return $this->_getNbByYear($sql); } @@ -163,7 +163,7 @@ * Return the invoices amount by month for a year * * @param int $year Year to scan - * @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 * @return array Array with amount by month */ public function getAmountByMonth($year, $format = 0) @@ -173,11 +173,11 @@ $sql = "SELECT date_format(datef,'%m') as dm, SUM(f.".$this->field.")"; $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= $this->join; + $sql .= $this->join; $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; - $sql .= " GROUP BY dm"; - $sql .= $this->db->order('dm', 'DESC'); + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); $res = $this->_getAmountByMonth($year, $sql, $format); //var_dump($res);print '
'; @@ -197,11 +197,11 @@ $sql = "SELECT date_format(datef,'%m') as dm, AVG(f.".$this->field.")"; $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= $this->join; - $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; + $sql .= $this->join; + $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; - $sql .= " GROUP BY dm"; - $sql .= $this->db->order('dm', 'DESC'); + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); return $this->_getAverageByMonth($year, $sql); } @@ -218,10 +218,10 @@ $sql = "SELECT date_format(datef,'%Y') as year, COUNT(*) as nb, SUM(f.".$this->field.") as total, AVG(f.".$this->field.") as avg"; $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= $this->join; + $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " GROUP BY year"; - $sql .= $this->db->order('year', 'DESC'); + $sql .= $this->db->order('year', 'DESC'); return $this->_getAllByYear($sql); } @@ -230,7 +230,7 @@ * Return nb, amount of predefined product for year * * @param int $year Year to scan - * @param int $limit Limit + * @param int $limit Limit * @return array Array of values */ public function getAllByProduct($year, $limit = 10) @@ -240,14 +240,14 @@ $sql = "SELECT product.ref, COUNT(product.ref) as nb, SUM(tl.".$this->field_line.") as total, AVG(tl.".$this->field_line.") as avg"; $sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= $this->join; + $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " AND f.rowid = tl.fk_facture AND tl.fk_product = product.rowid"; - $sql .= " AND f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year, 1, false))."' AND '".$this->db->idate(dol_get_last_day($year, 12, false))."'"; + $sql .= " AND f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year, 1, false))."' AND '".$this->db->idate(dol_get_last_day($year, 12, false))."'"; $sql .= " GROUP BY product.ref"; - $sql .= $this->db->order('nb', 'DESC'); - //$sql.= $this->db->plimit(20); - - return $this->_getAllByProduct($sql, $limit); + $sql .= $this->db->order('nb', 'DESC'); + //$sql.= $this->db->plimit(20); + + return $this->_getAllByProduct($sql, $limit); } } --- /tmp/dsg/dolibarr/htdocs/compta/facture/class/github_paymentterm.class.php +++ /tmp/dsg/dolibarr/htdocs/compta/facture/class/client_paymentterm.class.php @@ -28,9 +28,9 @@ class PaymentTerm // extends CommonObject { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -46,7 +46,7 @@ //public $table_element='c_payment_term'; //!< Name of table without prefix where object is stored public $context = array(); - /** + /** * @var int ID */ public $id; @@ -63,27 +63,27 @@ - /** - * Constructor - * + /** + * Constructor + * * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - - /** - * Create in database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs; + */ + public function __construct($db) + { + $this->db = $db; + } + + + /** + * Create in database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; $error = 0; // Clean parameters @@ -101,7 +101,7 @@ // Check parameters // Put here code to add control on parameters values - // Insert request + // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_payment_term("; $sql .= "entity,"; $sql .= "code,"; @@ -112,7 +112,7 @@ $sql .= "type_cdr,"; $sql .= "nbjour,"; $sql .= "decalage"; - $sql .= ") VALUES ("; + $sql .= ") VALUES ("; $sql .= " ".(!isset($this->entity) ?getEntity('c_payment_term') : "'".$this->db->escape($this->entity)."'").","; $sql .= " ".(!isset($this->code) ? 'NULL' : "'".$this->db->escape($this->code)."'").","; $sql .= " ".(!isset($this->sortorder) ? 'NULL' : "'".$this->db->escape($this->sortorder)."'").","; @@ -127,41 +127,43 @@ $this->db->begin(); dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_payment_term"); - } - - // Commit or rollback - if ($error) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_payment_term"); + } + + // Commit or rollback + if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); - return $this->id; - } - } - - - /** - * Load object in memory from database - * - * @param int $id Id object - * @return int <0 if KO, >0 if OK - */ - public function fetch($id) - { - global $langs; - $sql = "SELECT"; + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id Id object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id) + { + global $langs; + $sql = "SELECT"; $sql .= " t.rowid,"; $sql .= " t.entity,"; @@ -175,18 +177,18 @@ $sql .= " t.decalage"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; - $sql .= " WHERE t.rowid = ".$id; - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; + $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; + $sql .= " WHERE t.rowid = ".$id; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; $this->code = $obj->code; $this->sortorder = $obj->sortorder; @@ -196,22 +198,24 @@ $this->type_cdr = $obj->type_cdr; $this->nbjour = $obj->nbjour; $this->decalage = $obj->decalage; - } - $this->db->free($resql); - - return 1; - } else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } - - - /** - * Return id of default payment term - * - * @return int <0 if KO, >0 if OK - */ + } + $this->db->free($resql); + + return 1; + } + else + { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Return id of default payment term + * + * @return int <0 if KO, >0 if OK + */ public function getDefaultId() { global $langs; @@ -235,7 +239,9 @@ } $this->db->free($resql); return $ret; - } else { + } + else + { $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -243,12 +249,12 @@ /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function update($user = null, $notrigger = 0) { global $conf, $langs; @@ -299,7 +305,9 @@ } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return 1; } @@ -325,19 +333,21 @@ dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - - // Commit or rollback + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return 1; } @@ -386,22 +396,24 @@ { $this->db->commit(); return $object->id; - } else { + } + else + { $this->db->rollback(); return -1; } } - /** - * 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() - { + /** + * 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() + { $this->id = 0; $this->code = '';