api_thirdparties.class.php 55 KB

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