123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761 |
- <?php
- /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
- * Copyright (C) 2018 Pierre Chéné <pierre.chene44@gmail.com>
- * Copyright (C) 2019 Cedric Ancelin <icedo.anc@gmail.com>
- * Copyright (C) 2020-2021 Frédéric France <frederic.france@netlogic.fr>
- * Copyright (C) 2023 Alexandre Janniaux <alexandre.janniaux@gmail.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- */
- use Luracast\Restler\RestException;
- /**
- * API class for thirdparties
- *
- * @access protected
- * @class DolibarrApiAccess {@requires user,external}
- *
- */
- class Thirdparties extends DolibarrApi
- {
- /**
- *
- * @var array $FIELDS Mandatory fields, checked when create and update object
- */
- public static $FIELDS = array(
- 'name'
- );
- /**
- * @var Societe $company {@type Societe}
- */
- public $company;
- /**
- * Constructor
- */
- public function __construct()
- {
- global $db, $conf;
- $this->db = $db;
- require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
- require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
- require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
- require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
- $this->company = new Societe($this->db);
- if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY')) {
- static::$FIELDS[] = 'email';
- }
- }
- /**
- * Get properties of a thirdparty object
- *
- * Return an array with thirdparty informations
- *
- * @param int $id Id of third party to load
- * @return Object Object with cleaned properties
- *
- * @throws RestException
- */
- public function get($id)
- {
- return $this->_fetch($id);
- }
- /**
- * Get properties of a thirdparty object by email.
- *
- * Return an array with thirdparty informations
- *
- * @param string $email Email of third party to load
- * @return array|mixed Cleaned Societe object
- *
- * @url GET email/{email}
- *
- * @throws RestException
- */
- public function getByEmail($email)
- {
- return $this->_fetch('', '', '', '', '', '', '', '', '', '', $email);
- }
- /**
- * Get properties of a thirdparty object by barcode.
- *
- * Return an array with thirdparty informations
- *
- * @param string $barcode Barcode of third party to load
- * @return array|mixed Cleaned Societe object
- *
- * @url GET barcode/{barcode}
- *
- * @throws RestException
- */
- public function getByBarcode($barcode)
- {
- return $this->_fetch('', '', '', $barcode);
- }
- /**
- * List thirdparties
- *
- * Get a list of thirdparties
- *
- * @param string $sortfield Sort field
- * @param string $sortorder Sort order
- * @param int $limit Limit for list
- * @param int $page Page number
- * @param int $mode Set to 1 to show only customers
- * Set to 2 to show only prospects
- * Set to 3 to show only those are not customer neither prospect
- * Set to 4 to show only suppliers
- * @param int $category Use this param to filter list by category
- * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "((t.nom:like:'TheCompany%') or (t.name_alias:like:'TheCompany%')) and (t.datec:<:'20160101')"
- * @param string $properties Restrict the data returned to theses properties. Ignored if empty. Comma separated list of properties names
- * @return array Array of thirdparty objects
- */
- public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $properties = '')
- {
- $obj_ret = array();
- if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
- throw new RestException(401);
- }
- // case of external user, we force socids
- $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
- // 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."societe as t";
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields AS ef ON ef.fk_object = t.rowid"; // So we will be able to filter on extrafields
- if ($category > 0) {
- if ($mode != 4) {
- $sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c";
- }
- if (!in_array($mode, array(1, 2, 3))) {
- $sql .= ", ".MAIN_DB_PREFIX."categorie_fournisseur as cc";
- }
- }
- 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 .= ", ".MAIN_DB_PREFIX."c_stcomm as st";
- $sql .= " WHERE t.entity IN (".getEntity('societe').")";
- $sql .= " AND t.fk_stcomm = st.id";
- if ($mode == 1) {
- $sql .= " AND t.client IN (1, 3)";
- } elseif ($mode == 2) {
- $sql .= " AND t.client IN (2, 3)";
- } elseif ($mode == 3) {
- $sql .= " AND t.client IN (0)";
- } elseif ($mode == 4) {
- $sql .= " AND t.fournisseur IN (1)";
- }
- // Select thirdparties of given category
- if ($category > 0) {
- if (!empty($mode) && $mode != 4) {
- $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_soc = t.rowid";
- } elseif (!empty($mode) && $mode == 4) {
- $sql .= " AND cc.fk_categorie = ".((int) $category)." AND cc.fk_soc = t.rowid";
- } else {
- $sql .= " AND ((c.fk_categorie = ".((int) $category)." AND c.fk_soc = t.rowid) OR (cc.fk_categorie = ".((int) $category)." AND cc.fk_soc = t.rowid))";
- }
- }
- if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
- $sql .= " AND t.rowid = sc.fk_soc";
- }
- //if ($email != NULL) $sql.= " AND s.email = \"".$email."\"";
- if ($socids) {
- $sql .= " AND t.rowid IN (".$this->db->sanitize($socids).")";
- }
- if ($search_sale > 0) {
- $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
- }
- // Insert sale filter
- if ($search_sale > 0) {
- $sql .= " AND sc.fk_user = ".((int) $search_sale);
- }
- // Add sql filters
- if ($sqlfilters) {
- $errormessage = '';
- $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
- if ($errormessage) {
- throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
- }
- }
- $sql .= $this->db->order($sortfield, $sortorder);
- if ($limit) {
- if ($page < 0) {
- $page = 0;
- }
- $offset = $limit * $page;
- $sql .= $this->db->plimit($limit + 1, $offset);
- }
- $result = $this->db->query($sql);
- if ($result) {
- $num = $this->db->num_rows($result);
- $min = min($num, ($limit <= 0 ? $num : $limit));
- $i = 0;
- while ($i < $min) {
- $obj = $this->db->fetch_object($result);
- $soc_static = new Societe($this->db);
- if ($soc_static->fetch($obj->rowid)) {
- if (isModEnabled('mailing')) {
- $soc_static->getNoEmail();
- }
- $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($soc_static), $properties);
- }
- $i++;
- }
- } else {
- throw new RestException(503, 'Error when retrieve thirdparties : '.$this->db->lasterror());
- }
- if (!count($obj_ret)) {
- throw new RestException(404, 'Thirdparties not found');
- }
- return $obj_ret;
- }
- /**
- * Create thirdparty object
- *
- * @param array $request_data Request datas
- * @return int ID of thirdparty
- */
- public function post($request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- // Check mandatory fields
- $result = $this->_validate($request_data);
- foreach ($request_data as $field => $value) {
- $this->company->$field = $value;
- }
- if ($this->company->create(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, 'Error creating thirdparty', array_merge(array($this->company->error), $this->company->errors));
- }
- if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
- $this->company->setNoEmail($this->company->no_email);
- }
- return $this->company->id;
- }
- /**
- * Update thirdparty
- *
- * @param int $id Id of thirdparty to update
- * @param array $request_data Datas
- * @return array|mixed|boolean
- */
- public function put($id, $request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- foreach ($request_data as $field => $value) {
- if ($field == 'id') {
- continue;
- }
- $this->company->$field = $value;
- }
- if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
- $this->company->setNoEmail($this->company->no_email);
- }
- if ($this->company->update($id, DolibarrApiAccess::$user, 1, '', '', 'update', 1)) {
- return $this->get($id);
- }
- return false;
- }
- /**
- * Merge a thirdparty into another one.
- *
- * Merge content (properties, notes) and objects (like invoices, events, orders, proposals, ...) of a thirdparty into a target thirdparty,
- * then delete the merged thirdparty.
- * If a property has a defined value both in thirdparty to delete and thirdparty to keep, the value into the thirdparty to
- * delete will be ignored, the value of target thirdparty will remain, except for notes (content is concatenated).
- *
- * @param int $id ID of thirdparty to keep (the target thirdparty)
- * @param int $idtodelete ID of thirdparty to remove (the thirdparty to delete), once data has been merged into the target thirdparty.
- * @return int
- *
- * @url PUT {id}/merge/{idtodelete}
- */
- public function merge($id, $idtodelete)
- {
- global $user;
- $error = 0;
- if ($id == $idtodelete) {
- throw new RestException(400, 'Try to merge a thirdparty into itself');
- }
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $result = $this->company->fetch($id); // include the fetch of extra fields
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $companytoremove = new Societe($this->db);
- $result = $companytoremove->fetch($idtodelete); // include the fetch of extra fields
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $companytoremove->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $user = DolibarrApiAccess::$user;
- $result = $this->company->mergeCompany($companytoremove->id);
- if ($result < 0) {
- throw new RestException(500, 'Error failed to merged thirdparty '.$companytoremove->id.' into '.$id.'. Enable and read log file for more information.');
- }
- return $this->get($id);
- }
- /**
- * Delete thirdparty
- *
- * @param int $id Thirdparty ID
- * @return array
- */
- public function delete($id)
- {
- if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
- throw new RestException(401);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $this->company->oldcopy = clone $this->company;
- $res = $this->company->delete($id);
- if ($res < 0) {
- throw new RestException(500, "Can't delete, error occurs");
- } elseif ($res == 0) {
- throw new RestException(409, "Can't delete, that product is probably used");
- }
- return array(
- 'success' => array(
- 'code' => 200,
- 'message' => 'Object deleted'
- )
- );
- }
- /**
- * Set new price level for the given thirdparty
- *
- * @param int $id ID of thirdparty
- * @param int $priceLevel Price level to apply to thirdparty
- * @return object Thirdparty data without useless information
- *
- * @url PUT {id}/setpricelevel
- *
- * @throws RestException 400 Price level out of bounds
- * @throws RestException 401 Access not allowed for your login
- * @throws RestException 404 Thirdparty not found
- * @throws RestException 500 Error fetching/setting price level
- * @throws RestException 501 Request needs modules "Thirdparties" and "Products" and setting Multiprices activated
- */
- public function setThirdpartyPriceLevel($id, $priceLevel)
- {
- global $conf;
- if (!isModEnabled('societe')) {
- throw new RestException(501, 'Module "Thirdparties" needed for this request');
- }
- if (!isModEnabled("product")) {
- throw new RestException(501, 'Module "Products" needed for this request');
- }
- if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
- throw new RestException(501, 'Multiprices features activation needed for this request');
- }
- if ($priceLevel < 1 || $priceLevel > $conf->global->PRODUIT_MULTIPRICES_LIMIT) {
- throw new RestException(400, 'Price level must be between 1 and ' . getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT'));
- }
- if (empty(DolibarrApiAccess::$user->rights->societe->creer)) {
- throw new RestException(401, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $result = $this->company->fetch($id);
- if ($result < 0) {
- throw new RestException(404, 'Thirdparty '.$id.' not found');
- }
- if (empty($result)) {
- throw new RestException(500, 'Error fetching thirdparty '.$id, array_merge(array($this->company->error), $this->company->errors));
- }
- if (empty(DolibarrApi::_checkAccessToResource('societe', $this->company->id))) {
- throw new RestException(401, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $result = $this->company->setPriceLevel($priceLevel, DolibarrApiAccess::$user);
- if ($result <= 0) {
- throw new RestException(500, 'Error setting new price level for thirdparty '.$id, array($this->company->db->lasterror()));
- }
- return $this->_cleanObjectDatas($this->company);
- }
- /**
- * Get customer categories for a thirdparty
- *
- * @param int $id ID of thirdparty
- * @param string $sortfield Sort field
- * @param string $sortorder Sort order
- * @param int $limit Limit for list
- * @param int $page Page number
- * @return array|void
- *
- * @url GET {id}/categories
- */
- public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
- {
- if (!DolibarrApiAccess::$user->rights->categorie->lire) {
- throw new RestException(401);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $categories = new Categorie($this->db);
- $arrayofcateg = $categories->getListForItem($id, 'customer', $sortfield, $sortorder, $limit, $page);
- if (is_numeric($arrayofcateg) && $arrayofcateg < 0) {
- throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
- }
- if (is_numeric($arrayofcateg) && $arrayofcateg >= 0) { // To fix a return of 0 instead of empty array of method getListForItem
- return array();
- }
- return $arrayofcateg;
- }
- /**
- * Add a customer category to a thirdparty
- *
- * @param int $id Id of thirdparty
- * @param int $category_id Id of category
- * @return Object|void
- *
- * @url POST {id}/categories/{category_id}
- */
- public function addCategory($id, $category_id)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $category = new Categorie($this->db);
- $result = $category->fetch($category_id);
- if (!$result) {
- throw new RestException(404, 'category not found');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $category->add_type($this->company, 'customer');
- return $this->_cleanObjectDatas($this->company);
- }
- /**
- * Remove the link between a customer category and the thirdparty
- *
- * @param int $id Id of thirdparty
- * @param int $category_id Id of category
- *
- * @return Object|void
- *
- * @url DELETE {id}/categories/{category_id}
- */
- public function deleteCategory($id, $category_id)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $category = new Categorie($this->db);
- $result = $category->fetch($category_id);
- if (!$result) {
- throw new RestException(404, 'category not found');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $category->del_type($this->company, 'customer');
- return $this->_cleanObjectDatas($this->company);
- }
- /**
- * Get supplier categories for a thirdparty
- *
- * @param int $id ID of thirdparty
- * @param string $sortfield Sort field
- * @param string $sortorder Sort order
- * @param int $limit Limit for list
- * @param int $page Page number
- *
- * @return mixed
- *
- * @url GET {id}/supplier_categories
- */
- public function getSupplierCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
- {
- if (!DolibarrApiAccess::$user->rights->categorie->lire) {
- throw new RestException(401);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $categories = new Categorie($this->db);
- $result = $categories->getListForItem($id, 'supplier', $sortfield, $sortorder, $limit, $page);
- if (is_numeric($result) && $result < 0) {
- throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
- }
- if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
- return array();
- }
- return $result;
- }
- /**
- * Add a supplier category to a thirdparty
- *
- * @param int $id Id of thirdparty
- * @param int $category_id Id of category
- *
- * @return mixed
- *
- * @url POST {id}/supplier_categories/{category_id}
- */
- public function addSupplierCategory($id, $category_id)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $category = new Categorie($this->db);
- $result = $category->fetch($category_id);
- if (!$result) {
- throw new RestException(404, 'category not found');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $category->add_type($this->company, 'supplier');
- return $this->_cleanObjectDatas($this->company);
- }
- /**
- * Remove the link between a category and the thirdparty
- *
- * @param int $id Id of thirdparty
- * @param int $category_id Id of category
- *
- * @return mixed
- *
- * @url DELETE {id}/supplier_categories/{category_id}
- */
- public function deleteSupplierCategory($id, $category_id)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $category = new Categorie($this->db);
- $result = $category->fetch($category_id);
- if (!$result) {
- throw new RestException(404, 'category not found');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $category->del_type($this->company, 'supplier');
- return $this->_cleanObjectDatas($this->company);
- }
- /**
- * Get outstanding proposals of thirdparty
- *
- * @param int $id ID of the thirdparty
- * @param string $mode 'customer' or 'supplier'
- *
- * @url GET {id}/outstandingproposals
- *
- * @return array List of outstandings proposals of thirdparty
- *
- * @throws RestException 400
- * @throws RestException 401
- * @throws RestException 404
- */
- public function getOutStandingProposals($id, $mode = 'customer')
- {
- if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
- throw new RestException(401);
- }
- if (empty($id)) {
- throw new RestException(400, 'Thirdparty ID is mandatory');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $result = $this->company->getOutstandingProposals($mode);
- unset($result['total_ht']);
- unset($result['total_ttc']);
- return $result;
- }
- /**
- * Get outstanding orders of thirdparty
- *
- * @param int $id ID of the thirdparty
- * @param string $mode 'customer' or 'supplier'
- *
- * @url GET {id}/outstandingorders
- *
- * @return array List of outstandings orders of thirdparty
- *
- * @throws RestException 400
- * @throws RestException 401
- * @throws RestException 404
- */
- public function getOutStandingOrder($id, $mode = 'customer')
- {
- if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
- throw new RestException(401);
- }
- if (empty($id)) {
- throw new RestException(400, 'Thirdparty ID is mandatory');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $result = $this->company->getOutstandingOrders($mode);
- unset($result['total_ht']);
- unset($result['total_ttc']);
- return $result;
- }
- /**
- * Get outstanding invoices of thirdparty
- *
- * @param int $id ID of the thirdparty
- * @param string $mode 'customer' or 'supplier'
- *
- * @url GET {id}/outstandinginvoices
- *
- * @return array List of outstandings invoices of thirdparty
- *
- * @throws RestException 400
- * @throws RestException 401
- * @throws RestException 404
- */
- public function getOutStandingInvoices($id, $mode = 'customer')
- {
- if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
- throw new RestException(401);
- }
- if (empty($id)) {
- throw new RestException(400, 'Thirdparty ID is mandatory');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $result = $this->company->getOutstandingBills($mode);
- unset($result['total_ht']);
- unset($result['total_ttc']);
- return $result;
- }
- /**
- * Get representatives of thirdparty
- *
- * @param int $id ID of the thirdparty
- * @param string $mode 0=Array with properties, 1=Array of id.
- *
- * @url GET {id}/representatives
- *
- * @return array List of representatives of thirdparty
- *
- * @throws RestException 400
- * @throws RestException 401
- * @throws RestException 404
- */
- public function getSalesRepresentatives($id, $mode = 0)
- {
- if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
- throw new RestException(401);
- }
- if (empty($id)) {
- throw new RestException(400, 'Thirdparty ID is mandatory');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $result = $this->company->getSalesRepresentatives(DolibarrApiAccess::$user, $mode);
- return $result;
- }
- /**
- * Get fixed amount discount of a thirdparty (all sources: deposit, credit note, commercial offers...)
- *
- * @param int $id ID of the thirdparty
- * @param string $filter Filter exceptional discount. "none" will return every discount, "available" returns unapplied discounts, "used" returns applied discounts {@choice none,available,used}
- * @param string $sortfield Sort field
- * @param string $sortorder Sort order
- *
- * @url GET {id}/fixedamountdiscounts
- *
- * @return array List of fixed discount of thirdparty
- *
- * @throws RestException 400
- * @throws RestException 401
- * @throws RestException 404
- * @throws RestException 503
- */
- public function getFixedAmountDiscounts($id, $filter = "none", $sortfield = "f.type", $sortorder = 'ASC')
- {
- $obj_ret = array();
- if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
- throw new RestException(401);
- }
- if (empty($id)) {
- throw new RestException(400, 'Thirdparty ID is mandatory');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $result = $this->company->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- $sql = "SELECT f.ref, f.type as factype, re.fk_facture_source, re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc, re.description, re.fk_facture, re.fk_facture_line";
- $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re, ".MAIN_DB_PREFIX."facture as f";
- $sql .= " WHERE f.rowid = re.fk_facture_source AND re.fk_soc = ".((int) $id);
- if ($filter == "available") {
- $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL";
- }
- if ($filter == "used") {
- $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)";
- }
- $sql .= $this->db->order($sortfield, $sortorder);
- $result = $this->db->query($sql);
- if (!$result) {
- throw new RestException(503, $this->db->lasterror());
- } else {
- $num = $this->db->num_rows($result);
- while ($obj = $this->db->fetch_object($result)) {
- $obj_ret[] = $obj;
- }
- }
- return $obj_ret;
- }
- /**
- * Return list of invoices qualified to be replaced by another invoice.
- *
- * @param int $id Id of thirdparty
- *
- * @url GET {id}/getinvoicesqualifiedforreplacement
- *
- * @return array
- * @throws RestException 400
- * @throws RestException 401
- * @throws RestException 404
- * @throws RestException 405
- */
- public function getInvoicesQualifiedForReplacement($id)
- {
- if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
- throw new RestException(401);
- }
- if (empty($id)) {
- throw new RestException(400, 'Thirdparty ID is mandatory');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- /*$result = $this->thirdparty->fetch($id);
- if( ! $result ) {
- throw new RestException(404, 'Thirdparty not found');
- }*/
- $invoice = new Facture($this->db);
- $result = $invoice->list_replacable_invoices($id);
- if ($result < 0) {
- throw new RestException(405, $invoice->error);
- }
- return $result;
- }
- /**
- * Return list of invoices qualified to be corrected by a credit note.
- * Invoices matching the following rules are returned
- * (validated + payment on process) or classified (paid completely or paid partialy) + not already replaced + not already a credit note
- *
- * @param int $id Id of thirdparty
- *
- * @url GET {id}/getinvoicesqualifiedforcreditnote
- *
- * @return array
- *
- * @throws RestException 400
- * @throws RestException 401
- * @throws RestException 404
- * @throws RestException 405
- */
- public function getInvoicesQualifiedForCreditNote($id)
- {
- if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
- throw new RestException(401);
- }
- if (empty($id)) {
- throw new RestException(400, 'Thirdparty ID is mandatory');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- /*$result = $this->thirdparty->fetch($id);
- if( ! $result ) {
- throw new RestException(404, 'Thirdparty not found');
- }*/
- $invoice = new Facture($this->db);
- $result = $invoice->list_qualified_avoir_invoices($id);
- if ($result < 0) {
- throw new RestException(405, $invoice->error);
- }
- return $result;
- }
- /**
- * Get CompanyBankAccount objects for thirdparty
- *
- * @param int $id ID of thirdparty
- *
- * @return array
- *
- * @url GET {id}/bankaccounts
- */
- public function getCompanyBankAccount($id)
- {
- if (!DolibarrApiAccess::$user->rights->societe->lire) {
- throw new RestException(401);
- }
- if (empty($id)) {
- throw new RestException(400, 'Thirdparty ID is mandatory');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- /**
- * We select all the records that match the socid
- */
- $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,";
- $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur";
- $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
- if ($id) {
- $sql .= " WHERE fk_soc = ".((int) $id);
- }
- $result = $this->db->query($sql);
- if ($this->db->num_rows($result) == 0) {
- throw new RestException(404, 'Account not found');
- }
- $i = 0;
- $accounts = array();
- if ($result) {
- $num = $this->db->num_rows($result);
- while ($i < $num) {
- $obj = $this->db->fetch_object($result);
- $account = new CompanyBankAccount($this->db);
- if ($account->fetch($obj->rowid)) {
- $accounts[] = $account;
- }
- $i++;
- }
- } else {
- throw new RestException(404, 'Account not found');
- }
- $fields = array('socid', 'default_rib', 'frstrecur', '1000110000001', 'datec', 'datem', 'label', 'bank', 'bic', 'iban', 'id', 'rum');
- $returnAccounts = array();
- foreach ($accounts as $account) {
- $object = array();
- foreach ($account as $key => $value) {
- if (in_array($key, $fields)) {
- $object[$key] = $value;
- }
- }
- $returnAccounts[] = $object;
- }
- return $returnAccounts;
- }
- /**
- * Create CompanyBankAccount object for thirdparty
- * @param int $id ID of thirdparty
- * @param array $request_data Request data
- *
- * @return array|mixed BankAccount of thirdparty
- *
- * @url POST {id}/bankaccounts
- */
- public function createCompanyBankAccount($id, $request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- if ($this->company->fetch($id) <= 0) {
- throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
- }
- $account = new CompanyBankAccount($this->db);
- $account->socid = $id;
- foreach ($request_data as $field => $value) {
- $account->$field = $value;
- }
- if ($account->create(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, 'Error creating Company Bank account');
- }
- if (empty($account->rum)) {
- require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
- $prelevement = new BonPrelevement($this->db);
- $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
- $account->date_rum = dol_now();
- }
- if ($account->update(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, 'Error updating values');
- }
- return $this->_cleanObjectDatas($account);
- }
- /**
- * Update CompanyBankAccount object for thirdparty
- *
- * @param int $id ID of thirdparty
- * @param int $bankaccount_id ID of CompanyBankAccount
- * @param array $request_data Request data
- *
- * @return array|mixed BankAccount of thirdparty
- *
- * @url PUT {id}/bankaccounts/{bankaccount_id}
- */
- public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- if ($this->company->fetch($id) <= 0) {
- throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
- }
- $account = new CompanyBankAccount($this->db);
- $account->fetch($bankaccount_id, $id, -1, '');
- if ($account->socid != $id) {
- throw new RestException(401);
- }
- foreach ($request_data as $field => $value) {
- $account->$field = $value;
- }
- if (empty($account->rum)) {
- require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
- $prelevement = new BonPrelevement($this->db);
- $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
- $account->date_rum = dol_now();
- }
- if ($account->update(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, 'Error updating values');
- }
- return $this->_cleanObjectDatas($account);
- }
- /**
- * Delete a bank account attached to a thirdparty
- *
- * @param int $id ID of thirdparty
- * @param int $bankaccount_id ID of CompanyBankAccount
- *
- * @return int -1 if error 1 if correct deletion
- *
- * @url DELETE {id}/bankaccounts/{bankaccount_id}
- */
- public function deleteCompanyBankAccount($id, $bankaccount_id)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $account = new CompanyBankAccount($this->db);
- $account->fetch($bankaccount_id);
- if (!$account->socid == $id) {
- throw new RestException(401);
- }
- return $account->delete(DolibarrApiAccess::$user);
- }
- /**
- * Generate a Document from a bank account record (like SEPA mandate)
- *
- * @param int $id Thirdparty id
- * @param int $companybankid Companybank id
- * @param string $model Model of document to generate
- * @return array
- *
- * @url GET {id}/generateBankAccountDocument/{companybankid}/{model}
- */
- public function generateBankAccountDocument($id, $companybankid = null, $model = 'sepamandate')
- {
- global $conf, $langs;
- $langs->loadLangs(array("main", "dict", "commercial", "products", "companies", "banks", "bills", "withdrawals"));
- if ($this->company->fetch($id) <= 0) {
- throw new RestException(404, 'Thirdparty not found');
- }
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $this->company->setDocModel(DolibarrApiAccess::$user, $model);
- $this->company->fk_bank = $this->company->fk_account;
- $this->company->fk_account = $this->company->fk_account;
- $outputlangs = $langs;
- $newlang = '';
- //if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
- if (isset($this->company->thirdparty->default_lang)) {
- $newlang = $this->company->thirdparty->default_lang; // for proposal, order, invoice, ...
- } elseif (isset($this->company->default_lang)) {
- $newlang = $this->company->default_lang; // for thirdparty
- }
- }
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $sql = "SELECT rowid";
- $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
- if ($id) {
- $sql .= " WHERE fk_soc = ".((int) $id);
- }
- if ($companybankid) {
- $sql .= " AND rowid = ".((int) $companybankid);
- }
- $i = 0;
- $accounts = array();
- $result = $this->db->query($sql);
- if ($result) {
- if ($this->db->num_rows($result) == 0) {
- throw new RestException(404, 'Bank account not found');
- }
- $num = $this->db->num_rows($result);
- while ($i < $num) {
- $obj = $this->db->fetch_object($result);
- $account = new CompanyBankAccount($this->db);
- if ($account->fetch($obj->rowid)) {
- $accounts[] = $account;
- }
- $i++;
- }
- } else {
- throw new RestException(500, 'Sql error '.$this->db->lasterror());
- }
- $moreparams = array(
- 'use_companybankid' => $accounts[0]->id,
- 'force_dir_output' => $conf->societe->multidir_output[$this->company->entity].'/'.dol_sanitizeFileName($this->company->id)
- );
- $result = $this->company->generateDocument($model, $outputlangs, 0, 0, 0, $moreparams);
- if ($result > 0) {
- return array("success" => $result);
- } else {
- throw new RestException(500, 'Error generating the document '.$this->company->error);
- }
- }
- /**
- * Get a specific gateway attached to a thirdparty (by specifying the site key)
- *
- * @param int $id ID of thirdparty
- * @param string $site Site key
- *
- * @return array|mixed
- * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties
- * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
- *
- * @url GET {id}/gateways/
- */
- public function getSocieteAccounts($id, $site = null)
- {
- if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
- throw new RestException(401);
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- /**
- * We select all the records that match the socid
- */
- $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
- $sql .= " WHERE fk_soc = ".((int) $id);
- if ($site) {
- $sql .= " AND site ='".$this->db->escape($site)."'";
- }
- $result = $this->db->query($sql);
- if ($result && $this->db->num_rows($result) == 0) {
- throw new RestException(404, 'This thirdparty does not have any gateway attached or does not exist.');
- }
- $i = 0;
- $accounts = array();
- $num = $this->db->num_rows($result);
- while ($i < $num) {
- $obj = $this->db->fetch_object($result);
- $account = new SocieteAccount($this->db);
- if ($account->fetch($obj->rowid)) {
- $accounts[] = $account;
- }
- $i++;
- }
- $fields = array('id', 'fk_soc', 'key_account', 'site', 'date_creation', 'tms');
- $returnAccounts = array();
- foreach ($accounts as $account) {
- $object = array();
- foreach ($account as $key => $value) {
- if (in_array($key, $fields)) {
- $object[$key] = $value;
- }
- }
- $returnAccounts[] = $object;
- }
- return $returnAccounts;
- }
- /**
- * Create and attach a new gateway to an existing thirdparty
- *
- * Possible fields for request_data (request body) are specified in <code>llx_societe_account</code> table.<br>
- * See <a href="https://wiki.dolibarr.org/index.php/Table_llx_societe_account">Table llx_societe_account</a> wiki page for more information<br><br>
- * <u>Example body payload :</u> <pre>{"key_account": "cus_DAVkLSs1LYyYI", "site": "stripe"}</pre>
- *
- * @param int $id ID of thirdparty
- * @param array $request_data Request data
- *
- * @return array|mixed
- *
- * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties
- * @throws RestException 409 Conflict: A SocieteAccount entity (gateway) already exists for this company and site.
- * @throws RestException 422 Unprocessable Entity: You must pass the site attribute in your request data !
- * @throws RestException 500 Internal Server Error: Error creating SocieteAccount account
- *
- * @url POST {id}/gateways
- */
- public function createSocieteAccount($id, $request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- if (!isset($request_data['site'])) {
- throw new RestException(422, 'Unprocessable Entity: You must pass the site attribute in your request data !');
- }
- $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."'";
- $result = $this->db->query($sql);
- if ($result && $this->db->num_rows($result) == 0) {
- $account = new SocieteAccount($this->db);
- if (!isset($request_data['login'])) {
- $account->login = "";
- }
- $account->fk_soc = $id;
- foreach ($request_data as $field => $value) {
- $account->$field = $value;
- }
- if ($account->create(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, 'Error creating SocieteAccount entity. Ensure that the ID of thirdparty provided does exist!');
- }
- $this->_cleanObjectDatas($account);
- return $account;
- } else {
- throw new RestException(409, 'A SocieteAccount entity already exists for this company and site.');
- }
- }
- /**
- * Create and attach a new (or replace an existing) specific site gateway to a thirdparty
- *
- * You <strong>MUST</strong> pass all values to keep (otherwise, they will be deleted) !<br>
- * If you just need to update specific fields prefer <code>PATCH /thirdparties/{id}/gateways/{site}</code> endpoint.<br><br>
- * When a <strong>SocieteAccount</strong> entity does not exist for the <code>id</code> and <code>site</code>
- * supplied, a new one will be created. In that case <code>fk_soc</code> and <code>site</code> members form
- * request body payload will be ignored and <code>id</code> and <code>site</code> query strings parameters
- * will be used instead.
- *
- * @param int $id ID of thirdparty
- * @param string $site Site key
- * @param array $request_data Request data
- *
- * @return array|mixed
- *
- * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties
- * @throws RestException 422 Unprocessable Entity: You must pass the site attribute in your request data !
- * @throws RestException 500 Internal Server Error: Error updating SocieteAccount entity
- *
- * @url PUT {id}/gateways/{site}
- */
- public function putSocieteAccount($id, $site, $request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $sql = "SELECT rowid, fk_user_creat, date_creation FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
- $result = $this->db->query($sql);
- // We do not found an existing SocieteAccount entity for this fk_soc and site ; we then create a new one.
- if ($result && $this->db->num_rows == 0) {
- if (!isset($request_data['key_account'])) {
- throw new RestException(422, 'Unprocessable Entity: You must pass the key_account attribute in your request data !');
- }
- $account = new SocieteAccount($this->db);
- if (!isset($request_data['login'])) {
- $account->login = "";
- }
- foreach ($request_data as $field => $value) {
- $account->$field = $value;
- }
- $account->fk_soc = $id;
- $account->site = $site;
- if ($account->create(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, 'Error creating SocieteAccount entity.');
- }
- // We found an existing SocieteAccount entity, we are replacing it
- } else {
- if (isset($request_data['site']) && $request_data['site'] !== $site) {
- $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
- $result = $this->db->query($sql);
- if ($result && $this->db->num_rows($result) !== 0) {
- throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) from $site to ".$request_data['site']." but another SocieteAccount entity already exists with this site key.");
- }
- }
- $obj = $this->db->fetch_object($result);
- $account = new SocieteAccount($this->db);
- $account->id = $obj->rowid;
- $account->fk_soc = $id;
- $account->site = $site;
- if (!isset($request_data['login'])) {
- $account->login = "";
- }
- $account->fk_user_creat = $obj->fk_user_creat;
- $account->date_creation = $obj->date_creation;
- foreach ($request_data as $field => $value) {
- $account->$field = $value;
- }
- if ($account->update(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, 'Error updating SocieteAccount entity.');
- }
- }
- $this->_cleanObjectDatas($account);
- return $account;
- }
- /**
- * Update specified values of a specific gateway attached to a thirdparty
- *
- * @param int $id Id of thirdparty
- * @param string $site Site key
- * @param array $request_data Request data
- *
- * @return array|mixed
- *
- * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties
- * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
- * @throws RestException 409 Conflict: Another SocieteAccount entity already exists for this thirdparty with this site key.
- * @throws RestException 500 Internal Server Error: Error updating SocieteAccount entity
- *
- * @url PATCH {id}/gateways/{site}
- */
- public function patchSocieteAccount($id, $site, $request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($site)."'";
- $result = $this->db->query($sql);
- if ($result && $this->db->num_rows($result) == 0) {
- throw new RestException(404, "This thirdparty does not have $site gateway attached or does not exist.");
- } else {
- // If the user tries to edit the site member, we check first if
- if (isset($request_data['site']) && $request_data['site'] !== $site) {
- $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
- $result = $this->db->query($sql);
- if ($result && $this->db->num_rows($result) !== 0) {
- throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) site member from ".$site." to ".$request_data['site']." but another SocieteAccount entity already exists for this thirdparty with this site key.");
- }
- }
- $obj = $this->db->fetch_object($result);
- $account = new SocieteAccount($this->db);
- $account->fetch($obj->rowid);
- foreach ($request_data as $field => $value) {
- $account->$field = $value;
- }
- if ($account->update(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, 'Error updating SocieteAccount account');
- }
- $this->_cleanObjectDatas($account);
- return $account;
- }
- }
- /**
- * Delete a specific site gateway attached to a thirdparty (by gateway id)
- *
- * @param int $id ID of thirdparty
- * @param int $site Site key
- *
- * @return void
- * @throws RestException 401 Unauthorized: User does not have permission to delete thirdparties gateways
- * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
- * @throws RestException 500 Internal Server Error: Error deleting SocieteAccount entity
- *
- * @url DELETE {id}/gateways/{site}
- */
- public function deleteSocieteAccount($id, $site)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
- $result = $this->db->query($sql);
- if ($result && $this->db->num_rows($result) == 0) {
- throw new RestException(404);
- } else {
- $obj = $this->db->fetch_object($result);
- $account = new SocieteAccount($this->db);
- $account->fetch($obj->rowid);
- if ($account->delete(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, "Error while deleting $site gateway attached to this third party");
- }
- }
- }
- /**
- * Delete all gateways attached to a thirdparty
- *
- * @param int $id ID of thirdparty
- *
- * @return void
- * @throws RestException 401 Unauthorized: User does not have permission to delete thirdparties gateways
- * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
- * @throws RestException 500 Internal Server Error: Error deleting SocieteAccount entity
- *
- * @url DELETE {id}/gateways
- */
- public function deleteSocieteAccounts($id)
- {
- if (!DolibarrApiAccess::$user->rights->societe->creer) {
- throw new RestException(401);
- }
- /**
- * We select all the records that match the socid
- */
- $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms";
- $sql .= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id);
- $result = $this->db->query($sql);
- if ($result && $this->db->num_rows($result) == 0) {
- throw new RestException(404, 'This third party does not have any gateway attached or does not exist.');
- } else {
- $i = 0;
- $num = $this->db->num_rows($result);
- while ($i < $num) {
- $obj = $this->db->fetch_object($result);
- $account = new SocieteAccount($this->db);
- $account->fetch($obj->rowid);
- if ($account->delete(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, 'Error while deleting gateways attached to this third party');
- }
- $i++;
- }
- }
- }
- // 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->nom); // ->name already defined and nom deprecated
- unset($object->name_bis); // ->name_alias already defined
- unset($object->note); // ->note_private and note_public already defined
- unset($object->departement);
- unset($object->departement_code);
- unset($object->pays);
- unset($object->particulier);
- unset($object->prefix_comm);
- unset($object->siren);
- unset($object->siret);
- unset($object->ape);
- unset($object->commercial_id); // This property is used in create/update only. It does not exists in read mode because there is several sales representatives.
- unset($object->total_ht);
- unset($object->total_tva);
- unset($object->total_localtax1);
- unset($object->total_localtax2);
- unset($object->total_ttc);
- unset($object->lines);
- unset($object->thirdparty);
- unset($object->fk_delivery_address); // deprecated feature
- return $object;
- }
- /**
- * Validate fields before create or update object
- *
- * @param array $data Datas to validate
- * @return array
- *
- * @throws RestException
- */
- private function _validate($data)
- {
- $thirdparty = array();
- foreach (Thirdparties::$FIELDS as $field) {
- if (!isset($data[$field])) {
- throw new RestException(400, "$field field missing");
- }
- $thirdparty[$field] = $data[$field];
- }
- return $thirdparty;
- }
- /**
- * Fetch properties of a thirdparty object.
- *
- * Return an array with thirdparty informations
- *
- * @param int $rowid Id of third party to load (Use 0 to get a specimen record, use null to use other search criterias)
- * @param string $ref Reference of third party, name (Warning, this can return several records)
- * @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr)
- * @param string $barcode Barcode of third party to load
- * @param string $idprof1 Prof id 1 of third party (Warning, this can return several records)
- * @param string $idprof2 Prof id 2 of third party (Warning, this can return several records)
- * @param string $idprof3 Prof id 3 of third party (Warning, this can return several records)
- * @param string $idprof4 Prof id 4 of third party (Warning, this can return several records)
- * @param string $idprof5 Prof id 5 of third party (Warning, this can return several records)
- * @param string $idprof6 Prof id 6 of third party (Warning, this can return several records)
- * @param string $email Email of third party (Warning, this can return several records)
- * @param string $ref_alias Name_alias of third party (Warning, this can return several records)
- * @return array|mixed cleaned Societe object
- *
- * @throws RestException
- */
- private function _fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
- {
- global $conf;
- if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on thirdparties.');
- }
- if ($rowid === 0) {
- $result = $this->company->initAsSpecimen();
- } else {
- $result = $this->company->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias);
- }
- if (!$result) {
- throw new RestException(404, 'Thirdparty not found');
- }
- if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login.' on this thirdparty');
- }
- if (isModEnabled('mailing')) {
- $this->company->getNoEmail();
- }
- if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
- $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
- $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
- } else {
- $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
- $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
- }
- $absolute_discount = $this->company->getAvailableDiscounts('', $filterabsolutediscount);
- $absolute_creditnote = $this->company->getAvailableDiscounts('', $filtercreditnote);
- $this->company->absolute_discount = price2num($absolute_discount, 'MT');
- $this->company->absolute_creditnote = price2num($absolute_creditnote, 'MT');
- return $this->_cleanObjectDatas($this->company);
- }
- }
|