api_thirdparties.class.php 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908
  1. <?php
  2. /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  3. * Copyright (C) 2018 Pierre Chéné <pierre.chene44@gmail.com>
  4. * Copyright (C) 2019 Cedric Ancelin <icedo.anc@gmail.com>
  5. * Copyright (C) 2020-2021 Frédéric France <frederic.france@netlogic.fr>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. use Luracast\Restler\RestException;
  21. /**
  22. * API class for thirdparties
  23. *
  24. * @access protected
  25. * @class DolibarrApiAccess {@requires user,external}
  26. *
  27. */
  28. class Thirdparties extends DolibarrApi
  29. {
  30. /**
  31. *
  32. * @var array $FIELDS Mandatory fields, checked when create and update object
  33. */
  34. public static $FIELDS = array(
  35. 'name'
  36. );
  37. /**
  38. * @var Societe $company {@type Societe}
  39. */
  40. public $company;
  41. /**
  42. * Constructor
  43. */
  44. public function __construct()
  45. {
  46. global $db, $conf;
  47. $this->db = $db;
  48. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  49. require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
  50. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  51. require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
  52. $this->company = new Societe($this->db);
  53. if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY)) {
  54. static::$FIELDS[] = 'email';
  55. }
  56. }
  57. /**
  58. * Get properties of a thirdparty object
  59. *
  60. * Return an array with thirdparty informations
  61. *
  62. * @param int $id Id of third party to load
  63. * @return array|mixed Cleaned Societe object
  64. *
  65. * @throws RestException
  66. */
  67. public function get($id)
  68. {
  69. return $this->_fetch($id);
  70. }
  71. /**
  72. * Get properties of a thirdparty object by email.
  73. *
  74. * Return an array with thirdparty informations
  75. *
  76. * @param string $email Email of third party to load
  77. * @return array|mixed Cleaned Societe object
  78. *
  79. * @url GET email/{email}
  80. *
  81. * @throws RestException
  82. */
  83. public function getByEmail($email)
  84. {
  85. return $this->_fetch('', '', '', '', '', '', '', '', '', '', $email);
  86. }
  87. /**
  88. * Get properties of a thirdparty object by barcode.
  89. *
  90. * Return an array with thirdparty informations
  91. *
  92. * @param string $barcode Barcode of third party to load
  93. * @return array|mixed Cleaned Societe object
  94. *
  95. * @url GET barcode/{barcode}
  96. *
  97. * @throws RestException
  98. */
  99. public function getByBarcode($barcode)
  100. {
  101. return $this->_fetch('', '', '', $barcode);
  102. }
  103. /**
  104. * List thirdparties
  105. *
  106. * Get a list of thirdparties
  107. *
  108. * @param string $sortfield Sort field
  109. * @param string $sortorder Sort order
  110. * @param int $limit Limit for list
  111. * @param int $page Page number
  112. * @param int $mode Set to 1 to show only customers
  113. * Set to 2 to show only prospects
  114. * Set to 3 to show only those are not customer neither prospect
  115. * Set to 4 to show only suppliers
  116. * @param int $category Use this param to filter list by category
  117. * @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')"
  118. * @return array Array of thirdparty objects
  119. */
  120. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '')
  121. {
  122. $obj_ret = array();
  123. if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
  124. throw new RestException(401);
  125. }
  126. // case of external user, we force socids
  127. $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
  128. // If the internal user must only see his customers, force searching by him
  129. $search_sale = 0;
  130. if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
  131. $search_sale = DolibarrApiAccess::$user->id;
  132. }
  133. $sql = "SELECT t.rowid";
  134. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  135. $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)
  136. }
  137. $sql .= " FROM ".MAIN_DB_PREFIX."societe as t";
  138. if ($category > 0) {
  139. if ($mode != 4) {
  140. $sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c";
  141. }
  142. if (!in_array($mode, array(1, 2, 3))) {
  143. $sql .= ", ".MAIN_DB_PREFIX."categorie_fournisseur as cc";
  144. }
  145. }
  146. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  147. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
  148. }
  149. $sql .= ", ".MAIN_DB_PREFIX."c_stcomm as st";
  150. $sql .= " WHERE t.entity IN (".getEntity('societe').")";
  151. $sql .= " AND t.fk_stcomm = st.id";
  152. if ($mode == 1) {
  153. $sql .= " AND t.client IN (1, 3)";
  154. } elseif ($mode == 2) {
  155. $sql .= " AND t.client IN (2, 3)";
  156. } elseif ($mode == 3) {
  157. $sql .= " AND t.client IN (0)";
  158. } elseif ($mode == 4) {
  159. $sql .= " AND t.fournisseur IN (1)";
  160. }
  161. // Select thirdparties of given category
  162. if ($category > 0) {
  163. if (!empty($mode) && $mode != 4) {
  164. $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_soc = t.rowid";
  165. } elseif (!empty($mode) && $mode == 4) {
  166. $sql .= " AND cc.fk_categorie = ".((int) $category)." AND cc.fk_soc = t.rowid";
  167. } else {
  168. $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))";
  169. }
  170. }
  171. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  172. $sql .= " AND t.rowid = sc.fk_soc";
  173. }
  174. //if ($email != NULL) $sql.= " AND s.email = \"".$email."\"";
  175. if ($socids) {
  176. $sql .= " AND t.rowid IN (".$this->db->sanitize($socids).")";
  177. }
  178. if ($search_sale > 0) {
  179. $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
  180. }
  181. // Insert sale filter
  182. if ($search_sale > 0) {
  183. $sql .= " AND sc.fk_user = ".((int) $search_sale);
  184. }
  185. // Add sql filters
  186. if ($sqlfilters) {
  187. $errormessage = '';
  188. if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
  189. throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
  190. }
  191. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  192. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
  193. }
  194. $sql .= $this->db->order($sortfield, $sortorder);
  195. if ($limit) {
  196. if ($page < 0) {
  197. $page = 0;
  198. }
  199. $offset = $limit * $page;
  200. $sql .= $this->db->plimit($limit + 1, $offset);
  201. }
  202. $result = $this->db->query($sql);
  203. if ($result) {
  204. $num = $this->db->num_rows($result);
  205. $min = min($num, ($limit <= 0 ? $num : $limit));
  206. $i = 0;
  207. while ($i < $min) {
  208. $obj = $this->db->fetch_object($result);
  209. $soc_static = new Societe($this->db);
  210. if ($soc_static->fetch($obj->rowid)) {
  211. if (isModEnabled('mailing')) {
  212. $soc_static->getNoEmail();
  213. }
  214. $obj_ret[] = $this->_cleanObjectDatas($soc_static);
  215. }
  216. $i++;
  217. }
  218. } else {
  219. throw new RestException(503, 'Error when retrieve thirdparties : '.$this->db->lasterror());
  220. }
  221. if (!count($obj_ret)) {
  222. throw new RestException(404, 'Thirdparties not found');
  223. }
  224. return $obj_ret;
  225. }
  226. /**
  227. * Create thirdparty object
  228. *
  229. * @param array $request_data Request datas
  230. * @return int ID of thirdparty
  231. */
  232. public function post($request_data = null)
  233. {
  234. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  235. throw new RestException(401);
  236. }
  237. // Check mandatory fields
  238. $result = $this->_validate($request_data);
  239. foreach ($request_data as $field => $value) {
  240. $this->company->$field = $value;
  241. }
  242. if ($this->company->create(DolibarrApiAccess::$user) < 0) {
  243. throw new RestException(500, 'Error creating thirdparty', array_merge(array($this->company->error), $this->company->errors));
  244. }
  245. if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
  246. $this->company->setNoEmail($this->company->no_email);
  247. }
  248. return $this->company->id;
  249. }
  250. /**
  251. * Update thirdparty
  252. *
  253. * @param int $id Id of thirdparty to update
  254. * @param array $request_data Datas
  255. * @return array|mixed|boolean
  256. */
  257. public function put($id, $request_data = null)
  258. {
  259. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  260. throw new RestException(401);
  261. }
  262. $result = $this->company->fetch($id);
  263. if (!$result) {
  264. throw new RestException(404, 'Thirdparty not found');
  265. }
  266. if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
  267. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  268. }
  269. foreach ($request_data as $field => $value) {
  270. if ($field == 'id') {
  271. continue;
  272. }
  273. $this->company->$field = $value;
  274. }
  275. if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
  276. $this->company->setNoEmail($this->company->no_email);
  277. }
  278. if ($this->company->update($id, DolibarrApiAccess::$user, 1, '', '', 'update', 1)) {
  279. return $this->get($id);
  280. }
  281. return false;
  282. }
  283. /**
  284. * Merge a thirdparty into another one.
  285. *
  286. * Merge content (properties, notes) and objects (like invoices, events, orders, proposals, ...) of a thirdparty into a target thirdparty,
  287. * then delete the merged thirdparty.
  288. * If a property has a defined value both in thirdparty to delete and thirdparty to keep, the value into the thirdparty to
  289. * delete will be ignored, the value of target thirdparty will remain, except for notes (content is concatenated).
  290. *
  291. * @param int $id ID of thirdparty to keep (the target thirdparty)
  292. * @param int $idtodelete ID of thirdparty to remove (the thirdparty to delete), once data has been merged into the target thirdparty.
  293. * @return int
  294. *
  295. * @url PUT {id}/merge/{idtodelete}
  296. */
  297. public function merge($id, $idtodelete)
  298. {
  299. global $hookmanager;
  300. $error = 0;
  301. if ($id == $idtodelete) {
  302. throw new RestException(400, 'Try to merge a thirdparty into itself');
  303. }
  304. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  305. throw new RestException(401);
  306. }
  307. $result = $this->company->fetch($id); // include the fetch of extra fields
  308. if (!$result) {
  309. throw new RestException(404, 'Thirdparty not found');
  310. }
  311. if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
  312. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  313. }
  314. $this->companytoremove = new Societe($this->db);
  315. $result = $this->companytoremove->fetch($idtodelete); // include the fetch of extra fields
  316. if (!$result) {
  317. throw new RestException(404, 'Thirdparty not found');
  318. }
  319. if (!DolibarrApi::_checkAccessToResource('societe', $this->companytoremove->id)) {
  320. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  321. }
  322. $soc_origin = $this->companytoremove;
  323. $object = $this->company;
  324. $user = DolibarrApiAccess::$user;
  325. // Call same code than into action 'confirm_merge'
  326. $this->db->begin();
  327. // Recopy some data
  328. $object->client = $object->client | $soc_origin->client;
  329. $object->fournisseur = $object->fournisseur | $soc_origin->fournisseur;
  330. $listofproperties = array(
  331. 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'url', 'barcode',
  332. 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
  333. 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
  334. 'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency',
  335. 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
  336. 'model_pdf', 'fk_projet'
  337. );
  338. foreach ($listofproperties as $property) {
  339. if (empty($object->$property)) {
  340. $object->$property = $soc_origin->$property;
  341. }
  342. }
  343. // Concat some data
  344. $listofproperties = array(
  345. 'note_public', 'note_private'
  346. );
  347. foreach ($listofproperties as $property) {
  348. $object->$property = dol_concatdesc($object->$property, $soc_origin->$property);
  349. }
  350. // Merge extrafields
  351. if (is_array($soc_origin->array_options)) {
  352. foreach ($soc_origin->array_options as $key => $val) {
  353. if (empty($object->array_options[$key])) {
  354. $object->array_options[$key] = $val;
  355. }
  356. }
  357. }
  358. // Merge categories
  359. $static_cat = new Categorie($this->db);
  360. $custcats = $static_cat->containing($soc_origin->id, 'customer', 'id');
  361. $object->setCategories($custcats, 'customer');
  362. $suppcats = $static_cat->containing($soc_origin->id, 'supplier', 'id');
  363. $object->setCategories($suppcats, 'supplier');
  364. // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
  365. if ($soc_origin->code_client == $object->code_client
  366. || $soc_origin->code_fournisseur == $object->code_fournisseur
  367. || $soc_origin->barcode == $object->barcode) {
  368. dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
  369. $soc_origin->code_client = '';
  370. $soc_origin->code_fournisseur = '';
  371. $soc_origin->barcode = '';
  372. $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
  373. }
  374. // Update
  375. $result = $object->update($object->id, $user, 0, 1, 1, 'merge');
  376. if ($result < 0) {
  377. $error++;
  378. }
  379. // Move links
  380. if (!$error) {
  381. // This list is also into the societe/card.php file
  382. // TODO Mutualise the list into object societe.class.php
  383. $objects = array(
  384. 'Adherent' => '/adherents/class/adherent.class.php',
  385. 'Don' => '/don/class/don.class.php',
  386. 'Societe' => '/societe/class/societe.class.php',
  387. //'Categorie' => '/categories/class/categorie.class.php',
  388. 'ActionComm' => '/comm/action/class/actioncomm.class.php',
  389. 'Propal' => '/comm/propal/class/propal.class.php',
  390. 'Commande' => '/commande/class/commande.class.php',
  391. 'Facture' => '/compta/facture/class/facture.class.php',
  392. 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
  393. 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
  394. 'Mo' => '/mrp/class/mo.class.php',
  395. 'Contact' => '/contact/class/contact.class.php',
  396. 'Contrat' => '/contrat/class/contrat.class.php',
  397. 'Expedition' => '/expedition/class/expedition.class.php',
  398. 'Fichinter' => '/fichinter/class/fichinter.class.php',
  399. 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
  400. 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
  401. 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
  402. 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
  403. 'Delivery' => '/delivery/class/delivery.class.php',
  404. 'Product' => '/product/class/product.class.php',
  405. 'Project' => '/projet/class/project.class.php',
  406. 'Ticket' => '/ticket/class/ticket.class.php',
  407. 'User' => '/user/class/user.class.php',
  408. 'Account' => '/compta/bank/class/account.class.php',
  409. 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php'
  410. );
  411. //First, all core objects must update their tables
  412. foreach ($objects as $object_name => $object_file) {
  413. require_once DOL_DOCUMENT_ROOT.$object_file;
  414. if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $object->id)) {
  415. $error++;
  416. //setEventMessages($this->db->lasterror(), null, 'errors');
  417. }
  418. }
  419. }
  420. // External modules should update their ones too
  421. if (!$error) {
  422. $reshook = $hookmanager->executeHooks('replaceThirdparty', array(
  423. 'soc_origin' => $soc_origin->id,
  424. 'soc_dest' => $object->id
  425. ), $soc_dest, $action);
  426. if ($reshook < 0) {
  427. //setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  428. $error++;
  429. }
  430. }
  431. if (!$error) {
  432. $object->context = array('merge'=>1, 'mergefromid'=>$soc_origin->id);
  433. // Call trigger
  434. $result = $object->call_trigger('COMPANY_MODIFY', $user);
  435. if ($result < 0) {
  436. //setEventMessages($object->error, $object->errors, 'errors');
  437. $error++;
  438. }
  439. // End call triggers
  440. }
  441. if (!$error) {
  442. //We finally remove the old thirdparty
  443. if ($soc_origin->delete($soc_origin->id, $user) < 1) {
  444. $error++;
  445. }
  446. }
  447. // End of merge
  448. if ($error) {
  449. $this->db->rollback();
  450. throw new RestException(500, 'Error failed to merged thirdparty '.$this->companytoremove->id.' into '.$id.'. Enable and read log file for more information.');
  451. } else {
  452. $this->db->commit();
  453. }
  454. return $this->get($id);
  455. }
  456. /**
  457. * Delete thirdparty
  458. *
  459. * @param int $id Thirdparty ID
  460. * @return integer
  461. */
  462. public function delete($id)
  463. {
  464. if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
  465. throw new RestException(401);
  466. }
  467. $result = $this->company->fetch($id);
  468. if (!$result) {
  469. throw new RestException(404, 'Thirdparty not found');
  470. }
  471. if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
  472. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  473. }
  474. $this->company->oldcopy = clone $this->company;
  475. return $this->company->delete($id);
  476. }
  477. /**
  478. * Set new price level for the given thirdparty
  479. *
  480. * @param int $id ID of thirdparty
  481. * @param int $priceLevel Price level to apply to thirdparty
  482. * @return object Thirdparty data without useless information
  483. *
  484. * @url PUT {id}/setpricelevel
  485. *
  486. * @throws RestException 400 Price level out of bounds
  487. * @throws RestException 401 Access not allowed for your login
  488. * @throws RestException 404 Thirdparty not found
  489. * @throws RestException 500 Error fetching/setting price level
  490. * @throws RestException 501 Request needs modules "Thirdparties" and "Products" and setting Multiprices activated
  491. */
  492. public function setThirdpartyPriceLevel($id, $priceLevel)
  493. {
  494. global $conf;
  495. if (!isModEnabled('societe')) {
  496. throw new RestException(501, 'Module "Thirdparties" needed for this request');
  497. }
  498. if (empty($conf->product->enabled)) {
  499. throw new RestException(501, 'Module "Products" needed for this request');
  500. }
  501. if (empty($conf->global->PRODUIT_MULTIPRICES)) {
  502. throw new RestException(501, 'Multiprices features activation needed for this request');
  503. }
  504. if ($priceLevel < 1 || $priceLevel > $conf->global->PRODUIT_MULTIPRICES_LIMIT) {
  505. throw new RestException(400, 'Price level must be between 1 and '.$conf->global->PRODUIT_MULTIPRICES_LIMIT);
  506. }
  507. if (empty(DolibarrApiAccess::$user->rights->societe->creer)) {
  508. throw new RestException(401, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
  509. }
  510. $result = $this->company->fetch($id);
  511. if ($result < 0) {
  512. throw new RestException(404, 'Thirdparty '.$id.' not found');
  513. }
  514. if (empty($result)) {
  515. throw new RestException(500, 'Error fetching thirdparty '.$id, array_merge(array($this->company->error), $this->company->errors));
  516. }
  517. if (empty(DolibarrApi::_checkAccessToResource('societe', $this->company->id))) {
  518. throw new RestException(401, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
  519. }
  520. $result = $this->company->setPriceLevel($priceLevel, DolibarrApiAccess::$user);
  521. if ($result <= 0) {
  522. throw new RestException(500, 'Error setting new price level for thirdparty '.$id, array($this->company->db->lasterror()));
  523. }
  524. return $this->_cleanObjectDatas($this->company);
  525. }
  526. /**
  527. * Get customer categories for a thirdparty
  528. *
  529. * @param int $id ID of thirdparty
  530. * @param string $sortfield Sort field
  531. * @param string $sortorder Sort order
  532. * @param int $limit Limit for list
  533. * @param int $page Page number
  534. *
  535. * @return mixed
  536. *
  537. * @url GET {id}/categories
  538. */
  539. public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
  540. {
  541. if (!DolibarrApiAccess::$user->rights->categorie->lire) {
  542. throw new RestException(401);
  543. }
  544. $result = $this->company->fetch($id);
  545. if (!$result) {
  546. throw new RestException(404, 'Thirdparty not found');
  547. }
  548. $categories = new Categorie($this->db);
  549. $result = $categories->getListForItem($id, 'customer', $sortfield, $sortorder, $limit, $page);
  550. if (is_numeric($result) && $result < 0) {
  551. throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
  552. }
  553. if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
  554. return array();
  555. }
  556. return $result;
  557. }
  558. /**
  559. * Add a customer category to a thirdparty
  560. *
  561. * @param int $id Id of thirdparty
  562. * @param int $category_id Id of category
  563. *
  564. * @return mixed
  565. *
  566. * @url POST {id}/categories/{category_id}
  567. */
  568. public function addCategory($id, $category_id)
  569. {
  570. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  571. throw new RestException(401);
  572. }
  573. $result = $this->company->fetch($id);
  574. if (!$result) {
  575. throw new RestException(404, 'Thirdparty not found');
  576. }
  577. $category = new Categorie($this->db);
  578. $result = $category->fetch($category_id);
  579. if (!$result) {
  580. throw new RestException(404, 'category not found');
  581. }
  582. if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
  583. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  584. }
  585. if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
  586. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  587. }
  588. $category->add_type($this->company, 'customer');
  589. return $this->_cleanObjectDatas($this->company);
  590. }
  591. /**
  592. * Remove the link between a customer category and the thirdparty
  593. *
  594. * @param int $id Id of thirdparty
  595. * @param int $category_id Id of category
  596. *
  597. * @return mixed
  598. *
  599. * @url DELETE {id}/categories/{category_id}
  600. */
  601. public function deleteCategory($id, $category_id)
  602. {
  603. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  604. throw new RestException(401);
  605. }
  606. $result = $this->company->fetch($id);
  607. if (!$result) {
  608. throw new RestException(404, 'Thirdparty not found');
  609. }
  610. $category = new Categorie($this->db);
  611. $result = $category->fetch($category_id);
  612. if (!$result) {
  613. throw new RestException(404, 'category not found');
  614. }
  615. if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
  616. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  617. }
  618. if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
  619. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  620. }
  621. $category->del_type($this->company, 'customer');
  622. return $this->_cleanObjectDatas($this->company);
  623. }
  624. /**
  625. * Get supplier categories for a thirdparty
  626. *
  627. * @param int $id ID of thirdparty
  628. * @param string $sortfield Sort field
  629. * @param string $sortorder Sort order
  630. * @param int $limit Limit for list
  631. * @param int $page Page number
  632. *
  633. * @return mixed
  634. *
  635. * @url GET {id}/supplier_categories
  636. */
  637. public function getSupplierCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
  638. {
  639. if (!DolibarrApiAccess::$user->rights->categorie->lire) {
  640. throw new RestException(401);
  641. }
  642. $result = $this->company->fetch($id);
  643. if (!$result) {
  644. throw new RestException(404, 'Thirdparty not found');
  645. }
  646. $categories = new Categorie($this->db);
  647. $result = $categories->getListForItem($id, 'supplier', $sortfield, $sortorder, $limit, $page);
  648. if (is_numeric($result) && $result < 0) {
  649. throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
  650. }
  651. if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
  652. return array();
  653. }
  654. return $result;
  655. }
  656. /**
  657. * Add a supplier category to a thirdparty
  658. *
  659. * @param int $id Id of thirdparty
  660. * @param int $category_id Id of category
  661. *
  662. * @return mixed
  663. *
  664. * @url POST {id}/supplier_categories/{category_id}
  665. */
  666. public function addSupplierCategory($id, $category_id)
  667. {
  668. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  669. throw new RestException(401);
  670. }
  671. $result = $this->company->fetch($id);
  672. if (!$result) {
  673. throw new RestException(404, 'Thirdparty not found');
  674. }
  675. $category = new Categorie($this->db);
  676. $result = $category->fetch($category_id);
  677. if (!$result) {
  678. throw new RestException(404, 'category not found');
  679. }
  680. if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
  681. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  682. }
  683. if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
  684. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  685. }
  686. $category->add_type($this->company, 'supplier');
  687. return $this->_cleanObjectDatas($this->company);
  688. }
  689. /**
  690. * Remove the link between a category and the thirdparty
  691. *
  692. * @param int $id Id of thirdparty
  693. * @param int $category_id Id of category
  694. *
  695. * @return mixed
  696. *
  697. * @url DELETE {id}/supplier_categories/{category_id}
  698. */
  699. public function deleteSupplierCategory($id, $category_id)
  700. {
  701. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  702. throw new RestException(401);
  703. }
  704. $result = $this->company->fetch($id);
  705. if (!$result) {
  706. throw new RestException(404, 'Thirdparty not found');
  707. }
  708. $category = new Categorie($this->db);
  709. $result = $category->fetch($category_id);
  710. if (!$result) {
  711. throw new RestException(404, 'category not found');
  712. }
  713. if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
  714. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  715. }
  716. if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
  717. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  718. }
  719. $category->del_type($this->company, 'supplier');
  720. return $this->_cleanObjectDatas($this->company);
  721. }
  722. /**
  723. * Get outstanding proposals of thirdparty
  724. *
  725. * @param int $id ID of the thirdparty
  726. * @param string $mode 'customer' or 'supplier'
  727. *
  728. * @url GET {id}/outstandingproposals
  729. *
  730. * @return array List of outstandings proposals of thirdparty
  731. *
  732. * @throws RestException 400
  733. * @throws RestException 401
  734. * @throws RestException 404
  735. */
  736. public function getOutStandingProposals($id, $mode = 'customer')
  737. {
  738. if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
  739. throw new RestException(401);
  740. }
  741. if (empty($id)) {
  742. throw new RestException(400, 'Thirdparty ID is mandatory');
  743. }
  744. if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
  745. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  746. }
  747. $result = $this->company->fetch($id);
  748. if (!$result) {
  749. throw new RestException(404, 'Thirdparty not found');
  750. }
  751. $result = $this->company->getOutstandingProposals($mode);
  752. unset($result['total_ht']);
  753. unset($result['total_ttc']);
  754. return $result;
  755. }
  756. /**
  757. * Get outstanding orders of thirdparty
  758. *
  759. * @param int $id ID of the thirdparty
  760. * @param string $mode 'customer' or 'supplier'
  761. *
  762. * @url GET {id}/outstandingorders
  763. *
  764. * @return array List of outstandings orders of thirdparty
  765. *
  766. * @throws RestException 400
  767. * @throws RestException 401
  768. * @throws RestException 404
  769. */
  770. public function getOutStandingOrder($id, $mode = 'customer')
  771. {
  772. if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
  773. throw new RestException(401);
  774. }
  775. if (empty($id)) {
  776. throw new RestException(400, 'Thirdparty ID is mandatory');
  777. }
  778. if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
  779. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  780. }
  781. $result = $this->company->fetch($id);
  782. if (!$result) {
  783. throw new RestException(404, 'Thirdparty not found');
  784. }
  785. $result = $this->company->getOutstandingOrders($mode);
  786. unset($result['total_ht']);
  787. unset($result['total_ttc']);
  788. return $result;
  789. }
  790. /**
  791. * Get outstanding invoices of thirdparty
  792. *
  793. * @param int $id ID of the thirdparty
  794. * @param string $mode 'customer' or 'supplier'
  795. *
  796. * @url GET {id}/outstandinginvoices
  797. *
  798. * @return array List of outstandings invoices of thirdparty
  799. *
  800. * @throws RestException 400
  801. * @throws RestException 401
  802. * @throws RestException 404
  803. */
  804. public function getOutStandingInvoices($id, $mode = 'customer')
  805. {
  806. if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
  807. throw new RestException(401);
  808. }
  809. if (empty($id)) {
  810. throw new RestException(400, 'Thirdparty ID is mandatory');
  811. }
  812. if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
  813. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  814. }
  815. $result = $this->company->fetch($id);
  816. if (!$result) {
  817. throw new RestException(404, 'Thirdparty not found');
  818. }
  819. $result = $this->company->getOutstandingBills($mode);
  820. unset($result['total_ht']);
  821. unset($result['total_ttc']);
  822. return $result;
  823. }
  824. /**
  825. * Get representatives of thirdparty
  826. *
  827. * @param int $id ID of the thirdparty
  828. * @param string $mode 0=Array with properties, 1=Array of id.
  829. *
  830. * @url GET {id}/representatives
  831. *
  832. * @return array List of representatives of thirdparty
  833. *
  834. * @throws RestException 400
  835. * @throws RestException 401
  836. * @throws RestException 404
  837. */
  838. public function getSalesRepresentatives($id, $mode = 0)
  839. {
  840. if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
  841. throw new RestException(401);
  842. }
  843. if (empty($id)) {
  844. throw new RestException(400, 'Thirdparty ID is mandatory');
  845. }
  846. if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
  847. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  848. }
  849. $result = $this->company->fetch($id);
  850. if (!$result) {
  851. throw new RestException(404, 'Thirdparty not found');
  852. }
  853. $result = $this->company->getSalesRepresentatives(DolibarrApiAccess::$user, $mode);
  854. return $result;
  855. }
  856. /**
  857. * Get fixed amount discount of a thirdparty (all sources: deposit, credit note, commercial offers...)
  858. *
  859. * @param int $id ID of the thirdparty
  860. * @param string $filter Filter exceptional discount. "none" will return every discount, "available" returns unapplied discounts, "used" returns applied discounts {@choice none,available,used}
  861. * @param string $sortfield Sort field
  862. * @param string $sortorder Sort order
  863. *
  864. * @url GET {id}/fixedamountdiscounts
  865. *
  866. * @return array List of fixed discount of thirdparty
  867. *
  868. * @throws RestException 400
  869. * @throws RestException 401
  870. * @throws RestException 404
  871. * @throws RestException 503
  872. */
  873. public function getFixedAmountDiscounts($id, $filter = "none", $sortfield = "f.type", $sortorder = 'ASC')
  874. {
  875. $obj_ret = array();
  876. if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
  877. throw new RestException(401);
  878. }
  879. if (empty($id)) {
  880. throw new RestException(400, 'Thirdparty ID is mandatory');
  881. }
  882. if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
  883. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  884. }
  885. $result = $this->company->fetch($id);
  886. if (!$result) {
  887. throw new RestException(404, 'Thirdparty not found');
  888. }
  889. $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";
  890. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re, ".MAIN_DB_PREFIX."facture as f";
  891. $sql .= " WHERE f.rowid = re.fk_facture_source AND re.fk_soc = ".((int) $id);
  892. if ($filter == "available") {
  893. $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL";
  894. }
  895. if ($filter == "used") {
  896. $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)";
  897. }
  898. $sql .= $this->db->order($sortfield, $sortorder);
  899. $result = $this->db->query($sql);
  900. if (!$result) {
  901. throw new RestException(503, $this->db->lasterror());
  902. } else {
  903. $num = $this->db->num_rows($result);
  904. while ($obj = $this->db->fetch_object($result)) {
  905. $obj_ret[] = $obj;
  906. }
  907. }
  908. return $obj_ret;
  909. }
  910. /**
  911. * Return list of invoices qualified to be replaced by another invoice.
  912. *
  913. * @param int $id Id of thirdparty
  914. *
  915. * @url GET {id}/getinvoicesqualifiedforreplacement
  916. *
  917. * @return array
  918. * @throws RestException 400
  919. * @throws RestException 401
  920. * @throws RestException 404
  921. * @throws RestException 405
  922. */
  923. public function getInvoicesQualifiedForReplacement($id)
  924. {
  925. if (!DolibarrApiAccess::$user->rights->facture->lire) {
  926. throw new RestException(401);
  927. }
  928. if (empty($id)) {
  929. throw new RestException(400, 'Thirdparty ID is mandatory');
  930. }
  931. if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
  932. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  933. }
  934. /*$result = $this->thirdparty->fetch($id);
  935. if( ! $result ) {
  936. throw new RestException(404, 'Thirdparty not found');
  937. }*/
  938. $invoice = new Facture($this->db);
  939. $result = $invoice->list_replacable_invoices($id);
  940. if ($result < 0) {
  941. throw new RestException(405, $this->thirdparty->error);
  942. }
  943. return $result;
  944. }
  945. /**
  946. * Return list of invoices qualified to be corrected by a credit note.
  947. * Invoices matching the following rules are returned
  948. * (validated + payment on process) or classified (paid completely or paid partialy) + not already replaced + not already a credit note
  949. *
  950. * @param int $id Id of thirdparty
  951. *
  952. * @url GET {id}/getinvoicesqualifiedforcreditnote
  953. *
  954. * @return array
  955. *
  956. * @throws RestException 400
  957. * @throws RestException 401
  958. * @throws RestException 404
  959. * @throws RestException 405
  960. */
  961. public function getInvoicesQualifiedForCreditNote($id)
  962. {
  963. if (!DolibarrApiAccess::$user->rights->facture->lire) {
  964. throw new RestException(401);
  965. }
  966. if (empty($id)) {
  967. throw new RestException(400, 'Thirdparty ID is mandatory');
  968. }
  969. if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
  970. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  971. }
  972. /*$result = $this->thirdparty->fetch($id);
  973. if( ! $result ) {
  974. throw new RestException(404, 'Thirdparty not found');
  975. }*/
  976. $invoice = new Facture($this->db);
  977. $result = $invoice->list_qualified_avoir_invoices($id);
  978. if ($result < 0) {
  979. throw new RestException(405, $this->thirdparty->error);
  980. }
  981. return $result;
  982. }
  983. /**
  984. * Get CompanyBankAccount objects for thirdparty
  985. *
  986. * @param int $id ID of thirdparty
  987. *
  988. * @return array
  989. *
  990. * @url GET {id}/bankaccounts
  991. */
  992. public function getCompanyBankAccount($id)
  993. {
  994. if (!DolibarrApiAccess::$user->rights->facture->lire) {
  995. throw new RestException(401);
  996. }
  997. if (empty($id)) {
  998. throw new RestException(400, 'Thirdparty ID is mandatory');
  999. }
  1000. if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
  1001. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  1002. }
  1003. /**
  1004. * We select all the records that match the socid
  1005. */
  1006. $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,";
  1007. $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur";
  1008. $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
  1009. if ($id) {
  1010. $sql .= " WHERE fk_soc = ".((int) $id);
  1011. }
  1012. $result = $this->db->query($sql);
  1013. if ($result->num_rows == 0) {
  1014. throw new RestException(404, 'Account not found');
  1015. }
  1016. $i = 0;
  1017. $accounts = array();
  1018. if ($result) {
  1019. $num = $this->db->num_rows($result);
  1020. while ($i < $num) {
  1021. $obj = $this->db->fetch_object($result);
  1022. $account = new CompanyBankAccount($this->db);
  1023. if ($account->fetch($obj->rowid)) {
  1024. $accounts[] = $account;
  1025. }
  1026. $i++;
  1027. }
  1028. } else {
  1029. throw new RestException(404, 'Account not found');
  1030. }
  1031. $fields = array('socid', 'default_rib', 'frstrecur', '1000110000001', 'datec', 'datem', 'label', 'bank', 'bic', 'iban', 'id', 'rum');
  1032. $returnAccounts = array();
  1033. foreach ($accounts as $account) {
  1034. $object = array();
  1035. foreach ($account as $key => $value) {
  1036. if (in_array($key, $fields)) {
  1037. $object[$key] = $value;
  1038. }
  1039. }
  1040. $returnAccounts[] = $object;
  1041. }
  1042. return $returnAccounts;
  1043. }
  1044. /**
  1045. * Create CompanyBankAccount object for thirdparty
  1046. * @param int $id ID of thirdparty
  1047. * @param array $request_data Request data
  1048. *
  1049. * @return array|mixed BankAccount of thirdparty
  1050. *
  1051. * @url POST {id}/bankaccounts
  1052. */
  1053. public function createCompanyBankAccount($id, $request_data = null)
  1054. {
  1055. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  1056. throw new RestException(401);
  1057. }
  1058. if ($this->company->fetch($id) <= 0) {
  1059. throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
  1060. }
  1061. $account = new CompanyBankAccount($this->db);
  1062. $account->socid = $id;
  1063. foreach ($request_data as $field => $value) {
  1064. $account->$field = $value;
  1065. }
  1066. if ($account->create(DolibarrApiAccess::$user) < 0) {
  1067. throw new RestException(500, 'Error creating Company Bank account');
  1068. }
  1069. if (empty($account->rum)) {
  1070. require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
  1071. $prelevement = new BonPrelevement($this->db);
  1072. $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
  1073. $account->date_rum = dol_now();
  1074. }
  1075. if ($account->update(DolibarrApiAccess::$user) < 0) {
  1076. throw new RestException(500, 'Error updating values');
  1077. }
  1078. return $this->_cleanObjectDatas($account);
  1079. }
  1080. /**
  1081. * Update CompanyBankAccount object for thirdparty
  1082. *
  1083. * @param int $id ID of thirdparty
  1084. * @param int $bankaccount_id ID of CompanyBankAccount
  1085. * @param array $request_data Request data
  1086. *
  1087. * @return array|mixed BankAccount of thirdparty
  1088. *
  1089. * @url PUT {id}/bankaccounts/{bankaccount_id}
  1090. */
  1091. public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null)
  1092. {
  1093. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  1094. throw new RestException(401);
  1095. }
  1096. if ($this->company->fetch($id) <= 0) {
  1097. throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
  1098. }
  1099. $account = new CompanyBankAccount($this->db);
  1100. $account->fetch($bankaccount_id, $id, -1, '');
  1101. if ($account->socid != $id) {
  1102. throw new RestException(401);
  1103. }
  1104. foreach ($request_data as $field => $value) {
  1105. $account->$field = $value;
  1106. }
  1107. if (empty($account->rum)) {
  1108. require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
  1109. $prelevement = new BonPrelevement($this->db);
  1110. $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
  1111. $account->date_rum = dol_now();
  1112. }
  1113. if ($account->update(DolibarrApiAccess::$user) < 0) {
  1114. throw new RestException(500, 'Error updating values');
  1115. }
  1116. return $this->_cleanObjectDatas($account);
  1117. }
  1118. /**
  1119. * Delete a bank account attached to a thirdparty
  1120. *
  1121. * @param int $id ID of thirdparty
  1122. * @param int $bankaccount_id ID of CompanyBankAccount
  1123. *
  1124. * @return int -1 if error 1 if correct deletion
  1125. *
  1126. * @url DELETE {id}/bankaccounts/{bankaccount_id}
  1127. */
  1128. public function deleteCompanyBankAccount($id, $bankaccount_id)
  1129. {
  1130. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  1131. throw new RestException(401);
  1132. }
  1133. $account = new CompanyBankAccount($this->db);
  1134. $account->fetch($bankaccount_id);
  1135. if (!$account->socid == $id) {
  1136. throw new RestException(401);
  1137. }
  1138. return $account->delete(DolibarrApiAccess::$user);
  1139. }
  1140. /**
  1141. * Generate a Document from a bank account record (like SEPA mandate)
  1142. *
  1143. * @param int $id Thirdparty id
  1144. * @param int $companybankid Companybank id
  1145. * @param string $model Model of document to generate
  1146. * @return void
  1147. *
  1148. * @url GET {id}/generateBankAccountDocument/{companybankid}/{model}
  1149. */
  1150. public function generateBankAccountDocument($id, $companybankid = null, $model = 'sepamandate')
  1151. {
  1152. global $conf, $langs;
  1153. $langs->loadLangs(array("main", "dict", "commercial", "products", "companies", "banks", "bills", "withdrawals"));
  1154. if ($this->company->fetch($id) <= 0) {
  1155. throw new RestException(404, 'Thirdparty not found');
  1156. }
  1157. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  1158. throw new RestException(401);
  1159. }
  1160. $this->company->setDocModel(DolibarrApiAccess::$user, $model);
  1161. $this->company->fk_bank = $this->company->fk_account;
  1162. $outputlangs = $langs;
  1163. $newlang = '';
  1164. //if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
  1165. if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) {
  1166. if (isset($this->company->thirdparty->default_lang)) {
  1167. $newlang = $this->company->thirdparty->default_lang; // for proposal, order, invoice, ...
  1168. } elseif (isset($this->company->default_lang)) {
  1169. $newlang = $this->company->default_lang; // for thirdparty
  1170. }
  1171. }
  1172. if (!empty($newlang)) {
  1173. $outputlangs = new Translate("", $conf);
  1174. $outputlangs->setDefaultLang($newlang);
  1175. }
  1176. $sql = "SELECT rowid";
  1177. $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
  1178. if ($id) {
  1179. $sql .= " WHERE fk_soc = ".((int) $id);
  1180. }
  1181. if ($companybankid) {
  1182. $sql .= " AND rowid = ".((int) $companybankid);
  1183. }
  1184. $i = 0;
  1185. $accounts = array();
  1186. $result = $this->db->query($sql);
  1187. if ($result) {
  1188. if ($this->db->num_rows($result) == 0) {
  1189. throw new RestException(404, 'Bank account not found');
  1190. }
  1191. $num = $this->db->num_rows($result);
  1192. while ($i < $num) {
  1193. $obj = $this->db->fetch_object($result);
  1194. $account = new CompanyBankAccount($this->db);
  1195. if ($account->fetch($obj->rowid)) {
  1196. $accounts[] = $account;
  1197. }
  1198. $i++;
  1199. }
  1200. } else {
  1201. throw new RestException(500, 'Sql error '.$this->db->lasterror());
  1202. }
  1203. $moreparams = array(
  1204. 'use_companybankid' => $accounts[0]->id,
  1205. 'force_dir_output' => $conf->societe->multidir_output[$this->company->entity].'/'.dol_sanitizeFileName($this->company->id)
  1206. );
  1207. $result = $this->company->generateDocument($model, $outputlangs, 0, 0, 0, $moreparams);
  1208. if ($result > 0) {
  1209. return array("success" => $result);
  1210. } else {
  1211. throw new RestException(500, 'Error generating the document '.$this->error);
  1212. }
  1213. }
  1214. /**
  1215. * Get a specific gateway attached to a thirdparty (by specifying the site key)
  1216. *
  1217. * @param int $id ID of thirdparty
  1218. * @param string $site Site key
  1219. *
  1220. * @return array|mixed
  1221. * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties
  1222. * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
  1223. *
  1224. * @url GET {id}/gateways/
  1225. */
  1226. public function getSocieteAccounts($id, $site = null)
  1227. {
  1228. if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
  1229. throw new RestException(401);
  1230. }
  1231. if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
  1232. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  1233. }
  1234. /**
  1235. * We select all the records that match the socid
  1236. */
  1237. $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
  1238. $sql .= " WHERE fk_soc = ".((int) $id);
  1239. if ($site) {
  1240. $sql .= " AND site ='".$this->db->escape($site)."'";
  1241. }
  1242. $result = $this->db->query($sql);
  1243. if ($result && $this->db->num_rows($result) == 0) {
  1244. throw new RestException(404, 'This thirdparty does not have any gateway attached or does not exist.');
  1245. }
  1246. $i = 0;
  1247. $accounts = array();
  1248. $num = $this->db->num_rows($result);
  1249. while ($i < $num) {
  1250. $obj = $this->db->fetch_object($result);
  1251. $account = new SocieteAccount($this->db);
  1252. if ($account->fetch($obj->rowid)) {
  1253. $accounts[] = $account;
  1254. }
  1255. $i++;
  1256. }
  1257. $fields = array('id', 'fk_soc', 'key_account', 'site', 'date_creation', 'tms');
  1258. $returnAccounts = array();
  1259. foreach ($accounts as $account) {
  1260. $object = array();
  1261. foreach ($account as $key => $value) {
  1262. if (in_array($key, $fields)) {
  1263. $object[$key] = $value;
  1264. }
  1265. }
  1266. $returnAccounts[] = $object;
  1267. }
  1268. return $returnAccounts;
  1269. }
  1270. /**
  1271. * Create and attach a new gateway to an existing thirdparty
  1272. *
  1273. * Possible fields for request_data (request body) are specified in <code>llx_societe_account</code> table.<br>
  1274. * 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>
  1275. * <u>Example body payload :</u> <pre>{"key_account": "cus_DAVkLSs1LYyYI", "site": "stripe"}</pre>
  1276. *
  1277. * @param int $id ID of thirdparty
  1278. * @param array $request_data Request data
  1279. *
  1280. * @return array|mixed
  1281. *
  1282. * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties
  1283. * @throws RestException 409 Conflict: A SocieteAccount entity (gateway) already exists for this company and site.
  1284. * @throws RestException 422 Unprocessable Entity: You must pass the site attribute in your request data !
  1285. * @throws RestException 500 Internal Server Error: Error creating SocieteAccount account
  1286. *
  1287. * @url POST {id}/gateways
  1288. */
  1289. public function createSocieteAccount($id, $request_data = null)
  1290. {
  1291. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  1292. throw new RestException(401);
  1293. }
  1294. if (!isset($request_data['site'])) {
  1295. throw new RestException(422, 'Unprocessable Entity: You must pass the site attribute in your request data !');
  1296. }
  1297. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."'";
  1298. $result = $this->db->query($sql);
  1299. if ($result && $this->db->num_rows($result) == 0) {
  1300. $account = new SocieteAccount($this->db);
  1301. if (!isset($request_data['login'])) {
  1302. $account->login = "";
  1303. }
  1304. $account->fk_soc = $id;
  1305. foreach ($request_data as $field => $value) {
  1306. $account->$field = $value;
  1307. }
  1308. if ($account->create(DolibarrApiAccess::$user) < 0) {
  1309. throw new RestException(500, 'Error creating SocieteAccount entity. Ensure that the ID of thirdparty provided does exist!');
  1310. }
  1311. $this->_cleanObjectDatas($account);
  1312. return $account;
  1313. } else {
  1314. throw new RestException(409, 'A SocieteAccount entity already exists for this company and site.');
  1315. }
  1316. }
  1317. /**
  1318. * Create and attach a new (or replace an existing) specific site gateway to a thirdparty
  1319. *
  1320. * You <strong>MUST</strong> pass all values to keep (otherwise, they will be deleted) !<br>
  1321. * If you just need to update specific fields prefer <code>PATCH /thirdparties/{id}/gateways/{site}</code> endpoint.<br><br>
  1322. * When a <strong>SocieteAccount</strong> entity does not exist for the <code>id</code> and <code>site</code>
  1323. * supplied, a new one will be created. In that case <code>fk_soc</code> and <code>site</code> members form
  1324. * request body payload will be ignored and <code>id</code> and <code>site</code> query strings parameters
  1325. * will be used instead.
  1326. *
  1327. * @param int $id ID of thirdparty
  1328. * @param string $site Site key
  1329. * @param array $request_data Request data
  1330. *
  1331. * @return array|mixed
  1332. *
  1333. * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties
  1334. * @throws RestException 422 Unprocessable Entity: You must pass the site attribute in your request data !
  1335. * @throws RestException 500 Internal Server Error: Error updating SocieteAccount entity
  1336. *
  1337. * @url PUT {id}/gateways/{site}
  1338. */
  1339. public function putSocieteAccount($id, $site, $request_data = null)
  1340. {
  1341. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  1342. throw new RestException(401);
  1343. }
  1344. $sql = "SELECT rowid, fk_user_creat, date_creation FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
  1345. $result = $this->db->query($sql);
  1346. // We do not found an existing SocieteAccount entity for this fk_soc and site ; we then create a new one.
  1347. if ($result && $this->db->num_rows == 0) {
  1348. if (!isset($request_data['key_account'])) {
  1349. throw new RestException(422, 'Unprocessable Entity: You must pass the key_account attribute in your request data !');
  1350. }
  1351. $account = new SocieteAccount($this->db);
  1352. if (!isset($request_data['login'])) {
  1353. $account->login = "";
  1354. }
  1355. foreach ($request_data as $field => $value) {
  1356. $account->$field = $value;
  1357. }
  1358. $account->fk_soc = $id;
  1359. $account->site = $site;
  1360. if ($account->create(DolibarrApiAccess::$user) < 0) {
  1361. throw new RestException(500, 'Error creating SocieteAccount entity.');
  1362. }
  1363. // We found an existing SocieteAccount entity, we are replacing it
  1364. } else {
  1365. if (isset($request_data['site']) && $request_data['site'] !== $site) {
  1366. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
  1367. $result = $this->db->query($sql);
  1368. if ($result && $this->db->num_rows($result) !== 0) {
  1369. 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.");
  1370. }
  1371. }
  1372. $obj = $this->db->fetch_object($result);
  1373. $account = new SocieteAccount($this->db);
  1374. $account->id = $obj->rowid;
  1375. $account->fk_soc = $id;
  1376. $account->site = $site;
  1377. if (!isset($request_data['login'])) {
  1378. $account->login = "";
  1379. }
  1380. $account->fk_user_creat = $obj->fk_user_creat;
  1381. $account->date_creation = $obj->date_creation;
  1382. foreach ($request_data as $field => $value) {
  1383. $account->$field = $value;
  1384. }
  1385. if ($account->update(DolibarrApiAccess::$user) < 0) {
  1386. throw new RestException(500, 'Error updating SocieteAccount entity.');
  1387. }
  1388. }
  1389. $this->_cleanObjectDatas($account);
  1390. return $account;
  1391. }
  1392. /**
  1393. * Update specified values of a specific gateway attached to a thirdparty
  1394. *
  1395. * @param int $id Id of thirdparty
  1396. * @param string $site Site key
  1397. * @param array $request_data Request data
  1398. *
  1399. * @return array|mixed
  1400. *
  1401. * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties
  1402. * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
  1403. * @throws RestException 409 Conflict: Another SocieteAccount entity already exists for this thirdparty with this site key.
  1404. * @throws RestException 500 Internal Server Error: Error updating SocieteAccount entity
  1405. *
  1406. * @url PATCH {id}/gateways/{site}
  1407. */
  1408. public function patchSocieteAccount($id, $site, $request_data = null)
  1409. {
  1410. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  1411. throw new RestException(401);
  1412. }
  1413. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($site)."'";
  1414. $result = $this->db->query($sql);
  1415. if ($result && $this->db->num_rows($result) == 0) {
  1416. throw new RestException(404, "This thirdparty does not have $site gateway attached or does not exist.");
  1417. } else {
  1418. // If the user tries to edit the site member, we check first if
  1419. if (isset($request_data['site']) && $request_data['site'] !== $site) {
  1420. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
  1421. $result = $this->db->query($sql);
  1422. if ($result && $this->db->num_rows($result) !== 0) {
  1423. 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.");
  1424. }
  1425. }
  1426. $obj = $this->db->fetch_object($result);
  1427. $account = new SocieteAccount($this->db);
  1428. $account->fetch($obj->rowid);
  1429. foreach ($request_data as $field => $value) {
  1430. $account->$field = $value;
  1431. }
  1432. if ($account->update(DolibarrApiAccess::$user) < 0) {
  1433. throw new RestException(500, 'Error updating SocieteAccount account');
  1434. }
  1435. $this->_cleanObjectDatas($account);
  1436. return $account;
  1437. }
  1438. }
  1439. /**
  1440. * Delete a specific site gateway attached to a thirdparty (by gateway id)
  1441. *
  1442. * @param int $id ID of thirdparty
  1443. * @param int $site Site key
  1444. *
  1445. * @return void
  1446. * @throws RestException 401 Unauthorized: User does not have permission to delete thirdparties gateways
  1447. * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
  1448. * @throws RestException 500 Internal Server Error: Error deleting SocieteAccount entity
  1449. *
  1450. * @url DELETE {id}/gateways/{site}
  1451. */
  1452. public function deleteSocieteAccount($id, $site)
  1453. {
  1454. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  1455. throw new RestException(401);
  1456. }
  1457. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
  1458. $result = $this->db->query($sql);
  1459. if ($result && $this->db->num_rows($result) == 0) {
  1460. throw new RestException(404);
  1461. } else {
  1462. $obj = $this->db->fetch_object($result);
  1463. $account = new SocieteAccount($this->db);
  1464. $account->fetch($obj->rowid);
  1465. if ($account->delete(DolibarrApiAccess::$user) < 0) {
  1466. throw new RestException(500, "Error while deleting $site gateway attached to this third party");
  1467. }
  1468. }
  1469. }
  1470. /**
  1471. * Delete all gateways attached to a thirdparty
  1472. *
  1473. * @param int $id ID of thirdparty
  1474. *
  1475. * @return void
  1476. * @throws RestException 401 Unauthorized: User does not have permission to delete thirdparties gateways
  1477. * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
  1478. * @throws RestException 500 Internal Server Error: Error deleting SocieteAccount entity
  1479. *
  1480. * @url DELETE {id}/gateways
  1481. */
  1482. public function deleteSocieteAccounts($id)
  1483. {
  1484. if (!DolibarrApiAccess::$user->rights->societe->creer) {
  1485. throw new RestException(401);
  1486. }
  1487. /**
  1488. * We select all the records that match the socid
  1489. */
  1490. $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms";
  1491. $sql .= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id);
  1492. $result = $this->db->query($sql);
  1493. if ($result && $this->db->num_rows($result) == 0) {
  1494. throw new RestException(404, 'This third party does not have any gateway attached or does not exist.');
  1495. } else {
  1496. $i = 0;
  1497. $num = $this->db->num_rows($result);
  1498. while ($i < $num) {
  1499. $obj = $this->db->fetch_object($result);
  1500. $account = new SocieteAccount($this->db);
  1501. $account->fetch($obj->rowid);
  1502. if ($account->delete(DolibarrApiAccess::$user) < 0) {
  1503. throw new RestException(500, 'Error while deleting gateways attached to this third party');
  1504. }
  1505. $i++;
  1506. }
  1507. }
  1508. }
  1509. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  1510. /**
  1511. * Clean sensible object datas
  1512. *
  1513. * @param Object $object Object to clean
  1514. * @return array|mixed Object with cleaned properties
  1515. */
  1516. protected function _cleanObjectDatas($object)
  1517. {
  1518. // phpcs:enable
  1519. $object = parent::_cleanObjectDatas($object);
  1520. unset($object->nom); // ->name already defined and nom deprecated
  1521. unset($object->name_bis); // ->name_alias already defined
  1522. unset($object->note); // ->note_private and note_public already defined
  1523. unset($object->departement);
  1524. unset($object->departement_code);
  1525. unset($object->pays);
  1526. unset($object->particulier);
  1527. unset($object->prefix_comm);
  1528. unset($object->siren);
  1529. unset($object->siret);
  1530. unset($object->ape);
  1531. 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.
  1532. unset($object->total_ht);
  1533. unset($object->total_tva);
  1534. unset($object->total_localtax1);
  1535. unset($object->total_localtax2);
  1536. unset($object->total_ttc);
  1537. unset($object->lines);
  1538. unset($object->thirdparty);
  1539. unset($object->fk_delivery_address); // deprecated feature
  1540. unset($object->skype);
  1541. unset($object->twitter);
  1542. unset($object->facebook);
  1543. unset($object->linkedin);
  1544. unset($object->instagram);
  1545. unset($object->snapchat);
  1546. unset($object->googleplus);
  1547. unset($object->youtube);
  1548. unset($object->whatsapp);
  1549. return $object;
  1550. }
  1551. /**
  1552. * Validate fields before create or update object
  1553. *
  1554. * @param array $data Datas to validate
  1555. * @return array
  1556. *
  1557. * @throws RestException
  1558. */
  1559. private function _validate($data)
  1560. {
  1561. $thirdparty = array();
  1562. foreach (Thirdparties::$FIELDS as $field) {
  1563. if (!isset($data[$field])) {
  1564. throw new RestException(400, "$field field missing");
  1565. }
  1566. $thirdparty[$field] = $data[$field];
  1567. }
  1568. return $thirdparty;
  1569. }
  1570. /**
  1571. * Fetch properties of a thirdparty object.
  1572. *
  1573. * Return an array with thirdparty informations
  1574. *
  1575. * @param int $rowid Id of third party to load (Use 0 to get a specimen record, use null to use other search criterias)
  1576. * @param string $ref Reference of third party, name (Warning, this can return several records)
  1577. * @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr)
  1578. * @param string $barcode Barcode of third party to load
  1579. * @param string $idprof1 Prof id 1 of third party (Warning, this can return several records)
  1580. * @param string $idprof2 Prof id 2 of third party (Warning, this can return several records)
  1581. * @param string $idprof3 Prof id 3 of third party (Warning, this can return several records)
  1582. * @param string $idprof4 Prof id 4 of third party (Warning, this can return several records)
  1583. * @param string $idprof5 Prof id 5 of third party (Warning, this can return several records)
  1584. * @param string $idprof6 Prof id 6 of third party (Warning, this can return several records)
  1585. * @param string $email Email of third party (Warning, this can return several records)
  1586. * @param string $ref_alias Name_alias of third party (Warning, this can return several records)
  1587. * @return array|mixed cleaned Societe object
  1588. *
  1589. * @throws RestException
  1590. */
  1591. private function _fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
  1592. {
  1593. global $conf;
  1594. if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
  1595. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on thirdparties.');
  1596. }
  1597. if ($rowid === 0) {
  1598. $result = $this->company->initAsSpecimen();
  1599. } else {
  1600. $result = $this->company->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias);
  1601. }
  1602. if (!$result) {
  1603. throw new RestException(404, 'Thirdparty not found');
  1604. }
  1605. if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
  1606. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login.' on this thirdparty');
  1607. }
  1608. if (isModEnabled('mailing')) {
  1609. $this->company->getNoEmail();
  1610. }
  1611. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  1612. $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  1613. $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  1614. } else {
  1615. $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
  1616. $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
  1617. }
  1618. $absolute_discount = $this->company->getAvailableDiscounts('', $filterabsolutediscount);
  1619. $absolute_creditnote = $this->company->getAvailableDiscounts('', $filtercreditnote);
  1620. $this->company->absolute_discount = price2num($absolute_discount, 'MT');
  1621. $this->company->absolute_creditnote = price2num($absolute_creditnote, 'MT');
  1622. return $this->_cleanObjectDatas($this->company);
  1623. }
  1624. }